問題描述
我正在從串行端口讀取 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模板網!