Int to Byte with same value

330 views Asked by At

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.

2

There are 2 answers

3
M A On

You can't. byte can only store numbers between -128 and 127. When converting an integer that is not representable, loss of information is bound to happen.

To elaborate, when converting the int to byte, 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 do

int i2 = b & 0xFF;

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

0
AudioBubble On

The answer to my question of how to make a byte store the same value as an int when printed out is byte b = (byte) intVariable;. I understand 234 would not work as it exceeds the limit but I did not say I was using that number, It was an example I had given, though I understand now it was not helpful so sorry and thank you to all that tried.