I have and int and a byte, I need the byte value to be the same value as the int, All answers I have found end up like this:
int i = 234;
byte b = (byte) i;
System.out.println(b); // -22
int i2 = b & 0xFF;
System.out.println(i2); // 234
Now if my int is equaled to 234, i need my byte value when printed out to say 234, not -22, I understand why its printed out as -22 but its not what I need.
If anyone knows how to do this then please help me.
You can't.
byte
can only store numbers between-128
and127
. When converting an integer that is not representable, loss of information is bound to happen.To elaborate, when converting the
int
tobyte
, only the lowest 8 bits are considered.234
is representable in these 8 bits but the result is a negative number (-22
) because the MSB is 1. In your code, when you doit renders the number back to 32-bit integer with all bits except the lowest 8 set to zero. Therefore, the result is the same number
234
.