Incorrect widening or out-of-range shifts in integer arithmetic

Incorrect widening or out-of-range shifts in integer arithmetic

Description

Casting an int multiplication result to long widens a value that may already have overflowed during multiplication. A shift at or beyond the type’s bit width can also produce an unexpected result because of Java’s shift-distance rules. This is a calculation-correctness problem; its security impact depends on whether the result controls size limits, access decisions or similar behavior.

Potential impact

  • Incorrect size, count or index calculations
  • Unexpected bit masks and flags
  • Incorrect intermediate results affecting later operations

Remediation

  1. Cast one operand to long before multiplying.
  2. Use Math.multiplyExact if overflow must be reported as an error.
  3. Check that a shift distance is smaller than the target type’s bit width.
  4. If a wider result is needed, widen the value before shifting.

Examples

Widening multiplication

Before

java
public long calculateSize(int itemCount, int itemSize) {
    return (long) (itemCount * itemSize);
}

After

java
public long calculateSize(int itemCount, int itemSize) {
    return (long) itemCount * itemSize;
}

Explanation:

  • Before: The int multiplication happens before the cast and may already have overflowed.
  • After: Casting an operand first makes the multiplication use the long range.

Shift operations

Before

java
public int buildMask(int flags) {
    return flags << 32;
}

After

java
public long buildMask(int flags) {
    return ((long) flags) << 32;
}

Explanation:

  • Before: Java uses only the low five bits of an int shift distance, so shifting by 32 does not have the intended effect.
  • After: Widening to long first makes this a 64-bit operation.

References