ZigZagZebra - 3 months ago 39

Java Question

I'm new to Java and I am really confused about signed byte in Java.

`byte a = -128;`

byte b = 126;

System.out.println((byte)(a ^ b));

The output is -2. Can someone please explain why we get this? Is -2 the correct result for -128 XOR 126?

Another question is I have a byte b and I want it to XOR all possible bytes, my code is

`byte i = -128`

while (i <= 127) {

byte c = (byte) b ^ i;

i++;

}

Is it correct?

Answer

This about the representation of signed numbers in computers. They are represented as 2s-complement. This means:

```
126 = 0111 1110
-128 = 1000 0000
-2 = 1111 1110
```

Negative values in 2s-complement are formed by taking the absolute value as binary number, inverting all bits except the MSB, adding one to the result and setting the MSB which is used as sign-bit to 1, eg.:

```
-3:
0000 0011 absolute value (3)
0111 1100 invert all bits except MSB
0111 1101 add 1
1111 1101 set MSB to 1
```