Search code examples
javabitoperations

Bitwise and (&) operator


I read that doing a & 0x7fffffff masks just the sign bit and doesn't tampers with the other bits.

int a = Integer.MIN_VALUE;
System.out.println(a & 0x7fffffff);

But, this code outputs

0

instead of

2147483648

Why is that?


Solution

  • Removing the most significant bit makes sure you get a non-negative value. It does not ensure that the result is positive. (0 is non-negative as well.) Neither does it make sure that you get the absolute value of the negative value. (Which you never get.)

    Actually it will result in the following value for any negative int value: negative_value - Integer.MIN_VALUE.

    For the reasoning why it behaves like this you have to check how the two's complement is working: https://en.wikipedia.org/wiki/Two's_complement