I am trying to extract the first 49 bits from a 7 byte array. I approached this byte using masks and bit shifting as follows:
long byteVal = ((decryptedVCW[6] & 0xff)&((decryptedVCW[6] & 0xff)<<7)) | ((decryptedVCW[5] & 0xff) << 8) | ((decryptedVCW[4] & 0xff) << 16) | ((decryptedVCW[3] & 0xff) << 24) | ((decryptedVCW[2] & 0xff) << 32) | ((decryptedVCW[1] & 0xff) << 40) | ((decryptedVCW[0] & 0xff) << 48);
Where decryptedVCW is a 56 bit byte array.
The masking and bit shifting work as expected until the 32 bit shift '<<32'.
As an example, the hex for decryptedVCW is E865037A9C6424 of which in binary is:
11101000011001010000001101111010100111000110010000100100
When I perform the above shifting I get 7AFC6503 in binary:
1111010111111000110010100000011
Does anyone have any idea why the bit shifting falls apart at 32 upwards and how to go about solving this issue?
Many thanks Shiv
The type of decryptedVCW[2] & 0xff
is int
, since the first operand is byte
and the second is an int
literal.
When the first operand of the <<
operator is int
, you are shifting an int
, so if the second operand is 32, you'll get int
overflow.
You can cast the first operand of the <<
operator to long
:
(((long)(decryptedVCW[2] & 0xff)) << 32)
or you can force the first operand to be a long
by using a long
literal in the &
operation, as suggested by @shmosel :
(decryptedVCW[2] & 0xFFL) << 32