1
我有一個大小爲4096的字節數組。我用0xA2填充字段0,用0xF0填充字段1。Java:將byte []位移位操作轉換爲short
我的目標是將字段0向左移8位,然後對字段1執行OR操作並將其存儲到一個短變量中。
在紙上的結果應該是:
1010 0010 (0xA2)
>>shift left by 8 bits
1010 0010 0000 (0xA20)
>>OR-operation with field 1
1010 0010 0000 (0xA20)(field 0)
1111 0000 (0xF0)(field 1)
----------------------
1010 1111 0010 (0xAF2)
已經有a similar post但它只是幫助了一點點。 即使我投了它似乎切斷了轉移的位。 這是代碼。
public static void main(String[] args) {
byte[] myMem = new byte[4096];
myMem[0] = (byte)0xA2;
myMem[1] = (byte)0xF0;
short test = (short)(myMem[0] << 8 | myMem[1]);
}
調試器顯示以下值:
myMem[0] = -94 (which is correctly 0xA2)
myMem[1] = -16 (which is correctly 0xF0)
test = -16 (which is wrong, 0x00A2. Should be -23824 or 0xA2F0).
帶我做了一個合乎邏輯的錯誤,我想,我找不到它雖然。
有趣。我想我應該讀更多關於Java的字節數據類型。這是我在問自己爲什麼你的答案奏效後發現的帖子:http://stackoverflow.com/questions/19061544/bitwise-anding-with-0xff-is-important – RnBandCrunk