2 bytes to short java(2字节短java)
问题描述
我正在从串行端口读取 133 个长度的数据包,最后 2 个字节包含 CRC 值,2 个字节值我使用 java 制作单个(我认为是短的).这就是我所做的,
i'm reading 133 length packet from serialport,last 2 bytes contain CRC values,2 bytes value i've make single(short i think) using java. this what i have done,
short high=(-48 & 0x00ff);
short low=80;
short c=(short) ((high<<8)+low);
但我没有得到正确的结果,是因为签名值有问题吗?我该如何解决这个问题,请帮助我遇到麻烦
but i'm not getting correct result,is it problem because signed valued? how can i solve this problem,plz help me i'm in trouble
推荐答案
请记住,如果您对细节不太熟悉,则不必为位移而纠结.您可以使用 ByteBuffer 来帮助您:
Remember, you don't have to tie yourself in knots with bit shifting if you're not too familiar with the details. You can use a ByteBuffer to help you out:
ByteBuffer bb = ByteBuffer.allocate(2);
bb.order(ByteOrder.LITTLE_ENDIAN);
bb.put(firstByte);
bb.put(secondByte);
short shortVal = bb.getShort(0);
反之亦然,你可以先放一个短,然后再拉出字节.
And vice versa, you can put a short, then pull out bytes.
顺便说一下,按位运算会自动将操作数提升到至少一个 int 的宽度.真的没有不允许将一个字节移动超过 7 位"的概念以及其他似乎正在流传的谣言.
By the way, bitwise operations automatically promote the operands to at least the width of an int. There's really no notion of "not being allowed to shift a byte more than 7 bits" and other rumours that seem to be going round.
这篇关于2字节短java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:2字节短java


基础教程推荐
- Struts2 URL 无法访问 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01