Java Reference
In-Depth Information
See also Guideline 60 , “ Convert integers to floating-point for floating-point opera-
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.
Click here to view code image
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:
Click here to view code image
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.
Click here to view code image
int x = 2147483642; // 0x7ffffffa
x += 1.0f;
// x contains 2147483647 (0x7fffffff)
// after the computation
Search WWH ::




Custom Search