如何在Java中读取小于-128的负字节值
我正在使用串行端口从另一个系统读取数据。 我正在读取 133 字节的数据包。 第二个字节是数据包编号,第三个字节是数据包编号的负值。
问题是类型 byte
的范围为 -128 到 127。当我尝试读取 -129(超出字节范围)时,它将给出值为 127。
我应该做什么我可以得到-129吗?
I'm reading data from another system using the serial port. I'm reading packets of 133 bytes. The second byte is the packet number and the third byte is the negative value of the packet number.
The problem is that the type byte
has a range of -128 to 127. When I attempt to read -129 (outside the range of byte) it will give the value as 127.
What should I do so I can get -129?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您必须确定您期望字节值的范围。 例如,如果您期望范围为 -129 到 126,则可以使用。
顺便说一句,您的值不能超过 256。
You have to determine what range you expect byte values to have. if you expect the range -129 to 126 for example you can use.
BTW You cannot have more than 256 value.
你得到的是 127,因为一个字节只有 8 位,所以该值是环绕的。 -129 不适合 java 字节。 如果您想在给定变量中容纳 -129,则必须修改程序以至少使用 Shorts。
You are getting 127 because a byte is only 8 bits and so the value is wrapping around. -129 won't fit in a java byte. You will have to modify your program to use shorts at the least if you want to fit -129 in a given variable.
由于我不了解协议,我必须在这里猜测一下。
也许这两个值都应该在协议中被视为无符号(正)字节,
您可以稍后将它们转换为整数。
与此美国专利 6313763 相关吗? 但由于数据包的长度是固定的,我不明白。
一个字节中不可能存储比 256 范围“更大”的数字。 也许你误解了协议,它的高位和低位存储在两个字节中?
I have to guess here a little as I don't know the protocol.
Maybe boths values should be treated as unsigned (positive) bytes in the protocol,
they you can convert them to ints later.
Is it related to this Us Pat 6313763 ? But as the length of the packet is fixed, I don't get it.
It is not possible to store "bigger" numbers than the range 256 in a byte. Maybe you misunderstood the protocol, and its the high and low bits of an int stored in two bytes?
小于 -128 的值不适合有符号字节。 你需要读一篇短文等。
Values less than -128 dont fit into a signed byte. You need to read a short etc.