...
| Code Block | ||
|---|---|---|
| ||
// b[] is a byte array, initialized to 0xff
byte[] b = new byte[] {-1, -1, -1, -1};
int result = 0;
for (int i = 0; i < 4; i++) {
result = ((result << 8) + b[i]);
}
|
In the bitwise operation, the value of the byte array element {{Wiki Markup 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|AA. References#FindBugs 08]\].
Noncompliant Code Example
...
INT14-C. Avoid performing bitwise and arithmetic operations on the same data | |
INT14-CPP. Avoid performing bitwise and arithmetic operations on the same data |
Bibliography
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="6da7885e-f45e-49af-9982-0cb11adb489d"><ac:plain-text-body><![CDATA[ | [ [Steele 1977AA. References#Steele 1977] ] ]]></ac:plain-text-body></ac:structured-macro> |
...
03. Numeric Types and Operations (NUM) NUM02-J. Ensure that division and modulo operations do not result in divide-by-zero errors