Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

This noncompliant code example masks off the upper 24 bits of the promoted byte array element before performing the addition. The number of bits required to mask the sizes of byte and int are specified by the JLS. While this code calculates the correct result, it violates this guideline by combining bitwise and arithmetic operations on the same data.

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

...

This compliant solution masks off the upper 24 bits of the promoted byte array element. The result is then combined with result using a logical OR operation.

Code Block
bgColor#ffcccc#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));
}

...