问题描述
我正在读取数据,有些是1字节,有些是2字节,有些是3字节,等等.对于单字节
I am reading data some are 1 byte, some are are 2 byte, some are 3 byte etc. For single byte
byte qtySat = r.readByte();
对于2个字节,我读为
int serialNumber = r.readUnsignedShort();
阅读一切正常,效果很好.转换为十六进制格式显示时出现的问题是有趣的情况.例如
The reading is all fine and working well. The problem when I convert to show in hex format I get funny scenarios. For example for
Integer.toHexString(qtySat )
我得到的输出为ffffffce,但我只想要ce?
I get the output as ffffffce but I just want ce ?
然后输入Integer.toHexString(serialNumber)我得到输出,例如A1,但我希望前导00 A1导致这2字节的数据.我应该对Integer.toHexString进行哪些更改?
Then for Integer.toHexString(serialNumber)I get output as say A1 but I want the leading 00 A1 cause this 2 byte of data. What changes to Integer.toHexString should I do?
推荐答案
Integer.toHexString(qtySat )
为您提供了传递给它的int
值的二进制表示形式.如果传递负数byte
,它将变成相同值的负数int
,这说明了您看到的所有1
位.
Integer.toHexString(qtySat )
gives you a binary representation of the int
value passed to it. If you are passing a negative byte
, it will become a negative int
of the same value, which explains all the 1
bits you are seeing.
在转换为十六进制字符串之前,可以使用Integer.toHexString(qtySat & 0xff)
将除低8位以外的所有其他位设置为0.
You can use Integer.toHexString(qtySat & 0xff)
to set all the bits other than the low 8 bits to 0 before converting to hex String.
byte qtySat = (byte)0xce;
System.out.println (qtySat);
System.out.println (Integer.toHexString(qtySat & 0xff));
打印
-50
ce
这篇关于为什么要以单字节开头ffffff的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!