简体   繁体   中英

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 ffffff s?

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 .

Thank you @ajb and @sumit, I used both the answers,

int myInt = 144;

byte myByte = (byte) myInt;

char myChar = (char) (myByte & 0xFF);

System.out.println("myChar :"+Integer.toHexString(myChar));

o/p,

myChar : 90

Use the following code :

int myInt = 144;
byte myByte = (byte)myInt;
System.out.println(myByte & 0xFF);

In Java 8, use Byte.toUnsignedInt(myByte) as ajb said.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM