Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 279
divine Avatar asked Dec 27 '16 11:12

divine


People also ask

How bitwise operations are applied on negative numbers?

When representing integers using a fixed number of bits, negative numbers are typically represented using two's complement. If using n bit numbers, the two's complement of a number x with 0 ≤ x < 2 n 0 \leq x < 2^n 0≤x<2n is ( − x ) mod 2 n = 2 n − x (-x) \mathbin{\text{mod}} 2^n = 2^n - x (−x)mod2n=2n−x.

Can bitwise be negative?

The result of bitwise-AND can be negative, e.g. (-1) & (-1) is definitely -1 . However, if either operand is nonnegative, the result must also be nonnegative. This is because in 2's complement representation, a negative number must have its 31st bit set, and a nonnegative number must have its 31st bit cleared.

How does bitwise operator work in Java?

Bitwise operators are used to performing the manipulation of individual bits of a number. They can be used with any integral type (char, short, int, etc.). They are used when performing update and query operations of the Binary indexed trees. This operator is a binary operator, denoted by '|'.


2 Answers

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
like image 107
Eran Avatar answered Oct 05 '22 23:10

Eran


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.

like image 20
Ihor Dobrovolskyi Avatar answered Oct 06 '22 00:10

Ihor Dobrovolskyi