In SystemVerilog, when you assign a value from a wider integer (e.g., 32-bit integer or int) to a narrower type (e.g., 16-bit logic [15:0] or localparam [15:0]), the upper bits are truncated (dropped) without warning. This can lead to overflow issues if the original value doesn't fit in the narrower type.
How to Check for Overflow
To detect overflow when assigning an integer (or any wider type) to a 16-bit localparam, you need to check if the value fits in 16 bits before assignment.
Example
Suppose you have:
localparam integer WIDE_VAL = 70000;
localparam [15:0] NARROW_VAL = WIDE_VAL;
Here, WIDE_VAL is 70000, which is greater than the maximum value that can be represented by 16 bits (65535 for unsigned).
Overflow Check
You can use a static assertion ($error or assert) to check for overflow at elaboration time:
localparam integer WIDE_VAL = 70000;
localparam [15:0] NARROW_VAL = WIDE_VAL;
// Check for overflow (unsigned case)
initial begin
if (WIDE_VAL > 16'hFFFF) begin
$error("Overflow: WIDE_VAL (%0d) does not fit in 16 bits", WIDE_VAL);
end
end
Or, using assert (for synthesis tools that support it):
localparam integer WIDE_VAL = 70000;
localparam [15:0] NARROW_VAL = WIDE_VAL;
initial begin
assert (WIDE_VAL <= 16'hFFFF)
else $error("Overflow: WIDE_VAL (%0d) does not fit in 16 bits", WIDE_VAL);
end
For Signed Values
If the value is signed, check the signed range:
localparam integer WIDE_VAL = -40000;
localparam signed [15:0] NARROW_VAL = WIDE_VAL;
initial begin
if ((WIDE_VAL < -32768) || (WIDE_VAL > 32767)) begin
$error("Overflow: WIDE_VAL (%0d) does not fit in signed 16 bits", WIDE_VAL);
end
end
For localparam Only
If you want to do this at elaboration time (not runtime), you can use a constant expression and cause a compile-time error:
localparam integer WIDE_VAL = 70000;
localparam [15:0] NARROW_VAL = WIDE_VAL;
// This will cause a compile-time error if overflow occurs
localparam _check_overflow = (WIDE_VAL <= 16'hFFFF) ? 1 : $error("Overflow!");
However, $error in a constant expression is not supported by all tools. Some tools support assert in constant expressions:
localparam integer WIDE_VAL = 70000;
localparam [15:0] NARROW_VAL = WIDE_VAL;
initial begin
assert (WIDE_VAL <= 16'hFFFF)
else $fatal("Overflow: WIDE_VAL (%0d) does not fit in 16 bits", WIDE_VAL);
end
Summary Table
| Value Type | 16-bit Range | Check Expression |
|---|
| Unsigned | 0 to 65535 | WIDE_VAL <= 16'hFFFF |
| Signed | -32768 to 32767 | (WIDE_VAL >= -32768) && (WIDE_VAL <= 32767) |
In summary:
To check for overflow when assigning an integer to a 16-bit localparam, compare the value against the 16-bit range and use an assert or $error to flag overflow conditions.
If you need a code snippet for your specific use case, let me know!