int myInt = 144;
byte myByte = /* Byte conversion of myInt */;
输出应该为myByte : 90
(十六进制值为144)。
所以,我做了以下操作:
byte myByte = (byte)myInt;
我得到了myByte : ffffff90
的输出。:(
我该如何摆脱这些ffffff
?
byte
是一种有符号类型。它的值在-128到127的范围内,而144不在这个范围内。Java中没有无符号的byte类型。
如果您使用的是Java 8,则将其视为0到255范围内的值的方法是使用Byte.toUnsignedInt
:
String output = String.format("%x", Byte.toUnsignedInt(myByte));
int byteValue = (int)myByte & 0xFF;
String output = String.format("%x", byteValue);
在你执行这两项操作之前,请确保你真的需要使用 byte
。很可能你不需要,如果你要表示值为144,而没有必要使用 byte
,只需使用 int
即可。
感谢@ajb和@sumit,我使用了两个答案,
int myInt = 144;
byte myByte = (byte) myInt;
char myChar = (char) (myByte & 0xFF);
System.out.println("myChar :"+Integer.toHexString(myChar));
o/p,
myChar : 90
int
转换为byte
(尽管标题不正确),而是关于在将byte
转换回int
时如何去除额外的1位。投票重新开放 - 或许可以将其关闭为更合适的问题的重复。 - ajb