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


- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01
- 转换 ldap 日期 2022-01-01
- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
- 如何指定 CORS 的响应标头? 2022-01-01
- Eclipse 的最佳 XML 编辑器 2022-01-01
- 未找到/usr/local/lib 中的库 2022-01-01
- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
- 获取数字的最后一位 2022-01-01
- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01