1

I have a byte array of size 4096. I fill field 0 with 0xA2 and field 1 with 0xF0.

My goal is to shift field 0 by 8 bits to the left, then do an OR-operation with field 1 and store it into a short variable.

The result on paper should be:

     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)

There was already a similar post but it only helped a little. Even though I'm casting it seems to cut off the shifted bits. Here's the code.

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]);
    }

Debugger shows following values:

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). 

Somewhere I made a logical mistake I suppose, I can't find it though.

Community
  • 1
  • 1
thz
  • 187
  • 10

1 Answers1

3

use

    short test = (short)((myMem[0]  << 8) | ((myMem[1])& 0xff));
stinepike
  • 54,068
  • 14
  • 92
  • 112
  • 1
    Interesting. I guess I should've read more about Java's byte datatype. Here's the post I found after I asked myself why your answer worked: http://stackoverflow.com/questions/19061544/bitwise-anding-with-0xff-is-important – thz Apr 12 '17 at 20:09