I want to obtain the least 32 bits from a number of type long, so I perform bitwise operation "&" on the number with bits mask 0xFFFFFFFF, but the result is not correct, it still contains the other bits.
for example:
long a = 0x1234567890ab; long b = (a & 0xffffffff);
I expect the value of b to be 0x567890ab
but in practice, it is still 0x1234567890ab
Try this:
long a = 0x1234567890ab; long b = (a & 0xffffffffL);
0xffffffff
is a literal of type int
, for performing &
with long
it's promoted to type long
by sign extension, therefore it turns into 0xffffffffffffffff
. To avoid sign extension you need to write it as a literal of type long
: 0xffffffffL
.
Does using 0xffffffffL make any difference?
I think what happens is that 0xffffffff gets upcasted to a long, and since both int and long are signed it tries to keep the same sign.
So, since 0xffffffff is -1 as an int, it gets converted to -1 as a long, or 0xffffffffffffffff
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With