出于某種原因,我在 StackOverflow 上找不到這個問題的任何答案。如果已經回答,請指點我重復的帖子。謝謝!我有一個設備,它對信號進行增量編碼并將 2 個 4 位增量打包到一個byte. 我試圖通過將 的高 4 位和低 4 位byte分成兩個單獨的帶符號的ints.例如:byte packedByte = (byte) 0x0FF; // should represent the value -1, -1 in twos complementint upper = packedByte >> 4; // upper byte is easy, prints -1/* * A few goes at getting the lower 4 bits: */int lower = packedByte & 0x0F; // sign is not extended, prints 15lower = (packedByte << 4) >> 4; // doesn't work for positive valueslower = (byte)((byte)(packedByte << 4) >>> 4); // works, but this feels slow有任何想法嗎?
1 回答

溫溫醬
TA貢獻1752條經驗 獲得超4個贊
假設,正如吉姆加里森指出的那樣,你的半字節實際上只代表 -8 到正 7,你可以繼續做你在上面所做的事情,你可以對下面的部分做以下事情:(packedByte & 0x0F)-2*(packedByte & 0x08)
。這里的邏輯是,它保留 0 到 7(從中減去 0),但如果較低數字的符號位中有 1,則減去 2*8 即 16 以得到適當的負數。
添加回答
舉報
0/150
提交
取消