Bitwise and (&) operator

3

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?

java
bit
operations
asked on Stack Overflow Oct 1, 2015 by user3824413 • edited Oct 1, 2015 by T.J. Crowder

2 Answers

5

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.

  00000000000000000000000000000000

Source: https://en.wikipedia.org/wiki/Two%27s_complement

answered on Stack Overflow Oct 1, 2015 by Krzysztof Krasoń • edited Oct 1, 2015 by Krzysztof Krasoń
1

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

answered on Stack Overflow Oct 1, 2015 by Matthias Wimmer • edited Nov 29, 2018 by Timo Tijhof

User contributions licensed under CC BY-SA 3.0