thz
thz

Reputation: 217

Java: byte[] bit shift operation into short

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.

Upvotes: 1

Views: 556

Answers (1)

stinepike
stinepike

Reputation: 54682

use

    short test = (short)((myMem[0]  << 8) | ((myMem[1])& 0xff));

Upvotes: 3

Related Questions