I am trying to convert an int to byte.
int i = 128;
byte b = (byte) i;
I know the range of byte if -128 to 127 and the rule of storing an i
Logic is simple, Java numbers are always signed in two's complement.
Now a byte has 8 bits and 128 is 10000000. When you do
int i = 128
you end up with:
i == 00000000 00000000 00000000 10000000
When you cast it to a byte you the 24 most significative are truncated, so you end up with
b == 10000000
but a Java byte is signed, and 128 can't be represented, since it overflows and wraps around. So what happens is that the value ends up as 128 - 256 = -128 (that's because of two's complement).