2个字节来缩短java [英] 2 bytes to short java
问题描述
我正在读取来自serialport的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);
但是我没有得到正确的结果,是否因为签名有问题?
我怎么能解决这个问题,PLZ帮助我我遇到麻烦
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!