How to display a hex/byte value in Java

帅比萌擦擦* 提交于 2019-12-23 20:14:57

问题


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 ffffffs?


回答1:


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.




回答2:


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



回答3:


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.



来源:https://stackoverflow.com/questions/29553993/how-to-display-a-hex-byte-value-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!