Skip to content

Avoid Overflow when Left-Shifting

Problem

Shift operators act on the bit-width of the left operand. If the shift amount on the RHS is greater than or equal to that width, the result overflows to 0, which is usually meaningless.

bit [8] byteVal  = 8'h01;
bit [8] byteShift = byteVal << 9; //  byteShift: 0 -> 8'h00 (overflowed to zero)

PSS 3.1: a wider target widens the shift

PSS 3.1 defines how the width of a numeric expression is chosen (LRM 8.7). When an expression is assigned, a target wider than the expression is propagated into it, and a shift passes that width on to its left operand. So bit [16] r = byteVal << 9; shifts at 16 bits and gives 16'h0200. The overflow above happens because the target is as narrow as the operand, and it also happens wherever the shift is self-determined (no wider target is propagated into it). The solutions below do not depend on these rules, so they give the same result with any tool.

Solution

Make sure the shift happens at a width that can hold the result. Any one of the following works.

Declare the operand wide enough so the shift amount stays within its bit-width.

bit [16] wideVal   = 16'h0001;
bit [16] wideShift = wideVal << 9; //  wideShift: 0 -> 16'h0200 (fits without overflow)

Assign the narrow value into a wider destination before shifting.

1
2
3
bit [8 ] narrowVal = 8'h01;
bit [16] dstVal    = narrowVal;   //  extend to 16 bits first
dstVal = dstVal << 9;             //  dstVal: 0 -> 16'h0200

Cast the operand to a wider type before applying the shift.

bit [8]  byteVal   = 8'h01;
bit [16] castShift = (cast(bit [16]) byteVal) << 9; //  castShift: 0 -> 16'h0200

See also