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.
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.
Assign the narrow value into a wider destination before shifting.