Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Last CS and EX1.

...

In the bitwise operation, the value of the byte array element b[i] is promoted to an int by sign extension. When a byte array element contains a negative value (for example, 0xff), the sign extension propagates 1-bits into the upper 24 bits of the int. This behavior might be unexpected if the programmer is assuming that byte is an unsigned type. In this example, adding the promoted byte values to result fails to result in a packed integer representation of the bytes [FindBugs 2008].

See NUM01-J-EX1 for details about doing similar calculations for the purpose of serializing numbers into bytes.

Noncompliant Code Example

...

Code Block
bgColor#ccccff
byte[] b = new byte[] {-1, -1, -1, -1};
int result = 0;
for (int i = 0; i < 4; i++) {
  result = ((result << 8) | (b[i] & 0xff));
}

See NUM01-J-EX1 for details about doing similar calculations for the purpose of serializing numbers into bytes.

Exceptions

NUM01-EX0: Bitwise operations may be used to construct constant expressions.

...

Code Block
bgColor#ccccff
int limit = 0x1FFFF; // 2^17 - 1 = 131071

NUM01-J-EX1: Data that is normally treated arithmetically may be treated with bitwise operations for the purpose of serialization or deserialization. This alternative treatment is often required for reading or writing the data from a file or network socket. Bitwise operations are also permitted when reading or writing the data from a tightly packed data structure of bytes.

...