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
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 bytes 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.