divine
divine

Reputation: 4922

How do negative operands to bitwise operators work in Java?

-4 & -5 = -8 // How?
-4 & 5 = 4 // How?

I need an explanation for how the above results can be reached. I have no difficulties in solving with positive integers.

Upvotes: 7

Views: 2733

Answers (2)

Eran
Eran

Reputation: 394116

Just convert the integers to their binary representation (for negative integers, use two's complement) and run the bit-wise AND:

-4 11111..1100 &
-5 11111..1011

-8 11111..1000


-4 11111..1100 &
 5 00000..0101

 4 00000..0100

Upvotes: 10

Ihor Dobrovolskyi
Ihor Dobrovolskyi

Reputation: 1241

Let's see how numbers are representing:

positive four    0100          
negative four    1100
positive five    0101          
negative five    1011
negative eight   1000

If you try to do and operation manual, you get a result like this:

1100 (-4) & 1011 (-5) = 1000 (-8)
1100 (-4) & 0101 (5) = 0100 (4)

Here you can read more about this.

Upvotes: 3

Related Questions