Akshaya Amar
Akshaya Amar

Reputation: 179

Does the bitwise operators XOR and OR works differently on negative numbers unlike AND operator

I was trying various combination for better understanding of the XOR operator but I am not able to figure out how bitwise actually works under the hood in case of negative numbers because it's fine(as expected) in the case of positive numbers but producing different results in case of bitwise AND(&), bitwise XOR(^) and bitwise OR(|) case while applying the same logic for negative numbers.

In case of positive numbers:

x = 26;
y = 3;
System.out.println(x ^ y); // 25
System.out.println(x & y); // 2
System.out.println(x | y); // 27

11010 -> 26
00011 -> 3

Applying XOR    Applying AND    Applying OR
11010           11010           11010
00011           00011           00011
-----           -----           -----
11001 -> 25     00010 -> 2      11011 -> 27

Expected outputs as when analysing manually.

But, in case of negative number:

x = 26;
y = -3;
System.out.println(x ^ y); // -25
System.out.println(x & y); // 24
System.out.println(x | y); // -1


00000000000000000000000000011010 --> 26
11111111111111111111111111111101 --> -3(2s complement of -3)

         Applying XOR                            Applying OR       
00000000000000000000000000011010       00000000000000000000000000011010            
11111111111111111111111111111101       11111111111111111111111111111101            
--------------------------------       --------------------------------        
11111111111111111111111111100111       11111111111111111111111111111111

(not expected outputs because while analysing manually it's giving different output because if I will convert the result of XOR(11111111111111111111111111100111) and OR(11111111111111111111111111111111) into decimal, then it will give a huge number which is nowhere nearby the expected output)

Any suggestions what internally is being done with which I am not familiar with or the functionality of bitwise XOR(|), AND(&) and OR(|) under the hood in case of negative numbers

Upvotes: 0

Views: 538

Answers (1)

Eugene
Eugene

Reputation: 121048

It is how numbers are stored internally when they are negative. For example:

System.out.println(Integer.toBinaryString(26));
System.out.println(Integer.toBinaryString(-3));

will output:

0000000.............0000...11010 // the zeros in front are not shown
11111111111111111111111111111101

So now it should make sense what happens when you XOR or AND. They are represented with 32 bits, that is where your miss-understanding is.

Upvotes: 4

Related Questions