Raw Byte In Bitwise Operation
ID |
java.raw_byte_in_bitwise_operation |
Severity |
high |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Java |
Tags |
reliability |
Description
Reports a byte-typed operand — a byte[] element access, or a byte-typed local, field or
parameter — used unmasked in a shift (<<, >>, >>>), or in a bitwise |/& whose sibling
operand is, or contains, a shift.
Rationale
byte is signed in Java. Combining one with an int operand promotes it first, and a negative
byte’s leading bits are sign-extended to 1 rather than 0:
byte[] bytes = readBytes();
int decoded = 0;
for (byte b : bytes) {
decoded = (decoded << 8) | b; // Bug: a negative b sign-extends and corrupts every bit above it
}
Once any byte in the sequence is negative (its top bit set), every bit above it in decoded
becomes 1 from that point on, producing a value with no relation to the intended one. The
defect is invisible in code review unless the reviewer specifically checks the sign of every byte
that could flow through the expression.