Jyo the Whiff Jyo the Whiff - 1 year ago 66
Java Question

How to display a hex/byte value in Java

int myInt = 144;
byte myByte = /* Byte conversion of myInt */;

Output should be
myByte : 90
(hex value of 144).

So, I did:

byte myByte = (byte)myInt;

I got output of
myByte : ffffff90
. :(

How can I get rid of those

ajb ajb
Answer Source

byte is a signed type. Its values are in the range -128 to 127; 144 is not in this range. There is no unsigned byte type in Java.

If you are using Java 8, the way to treat this as a value in the range 0 to 255 is to use Byte.toUnsignedInt:

String output = String.format("%x", Byte.toUnsignedInt(myByte));

(I don't know how you formatted the integer for hex output. It doesn't matter.)

Pre-Java 8, the easiest way is

int byteValue = (int)myByte & 0xFF;
String output = String.format("%x", byteValue);

But before you do either of those, make sure you really want to use a byte. Chances are you don't need to. And if you want to represent the value 144, you shouldn't use a byte, if you don't need to. Just use an int.