Java Reference
In-Depth Information
tions
,” for more information about mixing integer and floating-point arithmetic.
Noncompliant Code Example (Left Shift)
This noncompliant code example shows integer promotion resulting from the use of the
bitwise OR operator.
byte[] b = new byte[4];
int result = 0;
for (int i = 0; i < 4; i++) {
result = (result << 8) | b[i];
}
Each byte array element issign-extended to32bits before it isusedasanoperand. Ifit
originally contained the value
0xff
, it would contain
0xffffffff
[FindBugs 2008]. This
causes
result
to contain a value other than the concatenation of the four array elements.
Compliant Solution (Left Shift)
This compliant solution masks off the upper 24 bits of the byte array element to achieve
the intended result:
byte[] b = new byte[4];
int result = 0;
for (int i = 0; i < 4; i++) {
result = (result << 8) | (b[i] & 0xff);
}
Noncompliant Code Example (Compound Addition and Assignment)
This noncompliant code example performs a compound assignment operation.
int x = 2147483642; // 0x7ffffffa
x += 1.0f;
// x contains 2147483647 (0x7fffffff)
// after the computation