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
You can simply use the following method:
byteValue()
This returns the value of this Integer as a byte.
You will need to either import Java.lang or type it out as:
Java.lang.Integer.byteValue()
Bytes are treated as signed values in Java; like you pointed out, the range of a byte is [-128,127]. Adding 1 to 127 flips the sign bit, which means that 127 + 1 = -128.
Casting to byte
doesn't mean int_value % byte_range
. It means that only the last 8 significant bits are kept in the byte
value. At first that seems to mean the same thing, but byte
s are signed.
The int
value 128
is the following bits:
00000000 00000000 00000000 10000000
When the last 8 bits are kept, this is the result:
10000000
Now, the most significant bit in the byte
is interpreted as -128, not +128 as it was in the int
.
The value 128
overflows a byte
, and the result is negative because of that most significant bit being set.
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).