Bit Operation Issue (shifting, masking, ...)

180 Views Asked by At

Why does this expression always result in -2,147,483,648 (11111111 11111111 11111111 11111111)? I don't get it. data[] is a byte-Array filled with some values.

(((int)data[29] & 0x00000001) << 31) | (((int)data[30]&0x000000FF)<<12) | (((int)data[31]&0x000000FF)<<4) | (((int)data[32]&0x000000FF)>>>4)

Thanks.

1

There are 1 best solutions below

4
On

I don't think your expression always returns min value of signed int. if all values in data array were zero, it would return zero.

I also don't think this would result in setting all bits to ones.

Following code (Java) where I use Integer.MAX_VALUE:

int max = Integer.MAX_VALUE;    //(2^31 - 1) - all bits apart from the sign are 1
System.out.print(Integer.toBinaryString(((max & 0x00000001) << 31) | ((max&0x000000FF)<<12) | ((max&0x000000FF)<<4) | ((max&0x000000FF)>>>4)));

returns:

10000000000011111111111111111111

using provided values:

System.out.print(Integer.toBinaryString(
        ((0b00101001 & 0x00000001) << 31) |
        ((0b11111111 & 0x000000FF) << 12) |
        ((0b11111001 & 0x000000FF) << 4)  |
        ((0b11001111 & 0x000000FF ) >>> 4))
);

returns:

10000000000011111111111110011100