Correctness - Bitwise OR of signed byte value

from:https://dev.eclipse.org/sonar/rules/show/findbugs:BIT_IOR_OF_SIGNED_BYTE?layout=false



Correctness - Bitwise OR of signed byte value

findbugs : BIT_IOR_OF_SIGNED_BYTE

Loads a value from a byte array and performs a bitwise OR withthat value. Values loaded from a byte array are sign extended to 32 bitsbefore any any bitwise operations are performed on the value.Thus, if b[0] contains the value 0xff, andx is initially 0, then the code ((x << 8) | b[0])  will sign extend 0xffto get 0xffffffff, and thus give the value0xffffffff as the result.

In particular, the following code for packing a byte array into an int is badly wrong:

int result = 0;
for(int i = 0; i < 4; i++) 
  result = ((result << 8) | b[i]);

The following idiom will work instead:

int result = 0;
for(int i = 0; i < 4; i++) 
  result = ((result << 8) | (b[i] & 0xff));


你可能感兴趣的:(values,loaded,performed)