buff.getInt() & 0xffffffffL is an identity?
bit-manipulation, bytebuffer, java
Solution
In short, it's because the method needs to convert a signed `int` (which all Java `int`s are) to an unsigned quantity.
If you were to just do `(long) buff.getInt()`, and `buff.getInt()` returned `-1`, you'd end up with `-1`. And that's a signed quantity -- not what the method is supposed to return.
So what the method does is forces `buff.getInt()` to become unsigned by ANDing the `int` bits with `0x00000000FFFFFFFF`. This effectively "reinterprets" the bits of the signed `int` as an unsigned `int` (really a signed `long`, but as only the lower 32 bits are ever going to be set, it works as an unsigned `int`), producing the desired result.
For example, (working with bytes for brevity).
Say `buff.getInt()` is really `buff.getByte()`, and returns `-1 == 0xFF`
Try to cast that to an `int`, you'll end up with `0xFFFFFFFF` -- still `-1`, due to the magic of sign extension.
However, mask that with `0xFF`, and you'll end up with `0x000000FF` == 255 -- the desired value.
I believe the explicit cast is unnecessary (it isn't on my machine), but I could be missing something...
Edit: Turns out the cast actually is unnecessary. From JLS section 5.6.2:
Widening primitive conversion (§5.1.2) is applied to convert either or both operands as specified by the following rules:
- If either operand is of type `double`, the other is converted to `double`.
- Otherwise,if either operand is of type `float`, the other is converted to `float`.
- Otherwise, if either operand is of type `long`, the other is converted to `long`.
- Otherwise, both operands are converted to type `int`.
Problem
Here is some code I have been looking at: ``` public static long getUnsignedInt(ByteBuffer buff) { return (long) (buff.getInt() & 0xffffffffL); } ``` Is there any reason to do `buff.getInt() & 0xffffffffL` (`0xffffffffL` has 32 bits of 1's in the 32 least significant bits)? It looks to me like the result will always be `buff.getInt()`.