Java – Correctly convert decimal value to byte value


I need to convert decimal value like

int dec = 129;

into a byte value like

byte frame2 = (byte) 129;

but as you might already have guessed, it converts into an unexpected value. I want the byte value to be literally 129 instead of -127 (value of frame2).

How could you achieve it in Java? I would appreciate an explanation as well.


Best Solution

You can't and most likely you don't need to. a byte is -128 to 127 by definition. However you can store any 256 different values in a byte if you want with encoding.

byte b = (byte) 129;
int i = b & 0xff; // == 129


byte b = (byte) (129 + Byte.MIN_VALUE);
int i = b - Byte.MIN_VALUE; // also 129.