問(wèn)題描述
我正在從串行端口讀取 133 個(gè)長(zhǎng)度的數(shù)據(jù)包,最后 2 個(gè)字節(jié)包含 CRC 值,2 個(gè)字節(jié)值我使用 java 制作單個(gè)(我認(rèn)為是短的).這就是我所做的,
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);
但我沒(méi)有得到正確的結(jié)果,是因?yàn)楹灻涤袉?wèn)題嗎?我該如何解決這個(gè)問(wèn)題,請(qǐng)幫助我遇到麻煩
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
推薦答案
請(qǐng)記住,如果您對(duì)細(xì)節(jié)不太熟悉,則不必為位移而糾結(jié).您可以使用 ByteBuffer 來(lái)幫助您:
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);
反之亦然,你可以先放一個(gè)短,然后再拉出字節(jié).
And vice versa, you can put a short, then pull out bytes.
順便說(shuō)一下,按位運(yùn)算會(huì)自動(dòng)將操作數(shù)提升到至少一個(gè) int 的寬度.真的沒(méi)有不允許將一個(gè)字節(jié)移動(dòng)超過(guò) 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.
這篇關(guān)于2字節(jié)短java的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!