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
Why is that?
Negative numbers in Java are stored as twos complement. So a min value has sign bit set and all others not set. So what you do is:
10000000000000000000000000000000 & 01111111111111111111111111111111
When you clear the sign bit you get zero.
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
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
User contributions licensed under CC BY-SA 3.0