https://www.ideone.com/gYreaO , why does this really happen? Why does it take the two's complement way to display the value?
byte a=123;
byte b=5;
byte c=(byte)(a+b);
System.out.println(c);
https://www.ideone.com/gYreaO , why does this really happen? Why does it take the two's complement way to display the value?
byte a=123;
byte b=5;
byte c=(byte)(a+b);
System.out.println(c);
A byte
which is 8bit
can holds 2^8 = 256
values, first 7b
for value, 1b
for sign, all in the 2-complement
way :
-128, -127, ... 0, 1, 2 ..., 126, 127
When you are as 127
, and you do +1
, it goes back the first value of the range because of the bonary operation
01111110 126
01111111 127
10000000 -128
10000001 -127
Exactly the same happens, with int
when you reach Integer.MAX_VALUE
System.out.println(Integer.MAX_VALUE + 1); // -2147483648
System.out.println(Integer.MAX_VALUE + 1 == Integer.MIN_VALUE); // true
The byte range is -128 to 127. Here is what happens when you add one to max range of byte:
0 1 1 1 1 1 1 1 --> 127
+ 0 0 0 0 0 0 0 1 --> 1
------------------
1 0 0 0 0 0 0 0 --> -128
Please note that leftmost bit is the sign bit and since the sign bit is set, you can get the value of the variable by two's complement.
The byte
data type has min value -128(=-2^7)
and max value 127(=2^7-1)
.
The addition (a+b)
produces the result:
128
(binary 10000000
for the int
data type) because it is converted to int
,
but the casting (byte)(a+b)
squeezes it back to 1 byte and you get -128
(binary 10000000
for the byte
data type).