...
Left- and right-shift operators are often employed to multiply or divide a number by a power of 2. This compromises code readability and portability for the sake of often-illusory speed gains. The JVM will usually make such optimizations automatically, and unlike a programmer, the JVM can optimize for the implementation details of the current platform.
Noncompliant Code Example (Left Shift)
In this noncompliant code example, both bit manipulation and arithmetic manipulation are performed on the integer x
. The result is a (prematurely) optimized statement that assigns 5x + 1
to x
for implementations, where integers are represented as two's complement values.
Code Block | ||
---|---|---|
| ||
int x = 50; x += (x << 2) + 1; |
Compliant Solution (Left Shift)
In this compliant solution, the assignment statement is modified to reflect the arithmetic nature of x
, resulting in a clearer indication of the programmer's intentions.
...
A reviewer may now recognize that the operation should also be checked for overflow. This might not have been apparent in the original, noncompliant code example. For more information, see INT00-J. Ensure that integer operations do not result in overflow.
Noncompliant Code Example (Right Shift)
In this noncompliant code example, the programmer prematurely optimizes code by replacing a division with a right shift.
...
Although this code will perform the division correctly, it is less readable and maintainable than actually making the division explicit.
Compliant Solution (Right Shift)
In this compliant solution, the right shift is replaced by division.
Code Block | ||
---|---|---|
| ||
int x = -50; x += 2 x /= 4; |
Exceptions
INT03-EX1: Bitwise operations may be used to construct constant expressions.
...
Code Block | ||
---|---|---|
| ||
int value = /* interesting value */ Byte bytes[] = new Byte[4]; for (int i = 0; i < bytes.length; i++) { bytes[i] = value >> (i*8) & 0xFF; } /* bytes[] now has same bit representation as value */ |
Risk Assessment
Performing bit manipulation and arithmetic operations on the same variable obscures the programmer's intentions and reduces readability. This in turn makes it more difficult for a security auditor or maintainer to determine which checks must be performed to eliminate security flaws and ensure data integrity.
Recommendation | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
NUM03 NUM01-J | medium | unlikely | medium | P4 | L3 |
Related Guidelines
CERT C Secure Coding Standard: INT14-C. Avoid performing bitwise and arithmetic operations on the same data
CERT C++ Secure Coding Standard: INT14-CPP. Avoid performing bitwise and arithmetic operations on the same data
Bibliography
Wiki Markup |
---|
\[[Steele 1977|AA. Bibliography#Steele 77]\] |
...