我正在从串行端口读取 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!