I would like to create a parametric bit-width assignment in Verilog.
Something like the following code:
module COUNTER
(
CLEAR,
CLK,
CODE)
#(parameter BUS_WIDTH = 8)
reg [BUS_WIDTH-1:0] CODE;
always @(posedge CLK or posedge CLEAR)
begin
if(CLEAR)
begin
CODE <= BUS_WIDTH'b{BUS_WIDTH{0}};
CODEreg <= BUS_WIDTH'b{BUS_WIDTH{0}};
end
...
What is the right way for it to be synthesizable?
2 Answers 2
You were very close. The proper syntax is as follows:
CODE <= {BUS_WIDTH{1'b0}};
CODEreg <= {BUS_WIDTH{1'b0}};
Refer to IEEE Std 1800-2017, section 11.4.12.1 Replication operator.
The one bit value (1'b0
) is replicated 8 times to form the 8-bit value (8'b0000_0000
).
This is synthesizable.
This is also called a multiple concatenation.
There is no need to do this unless you have linting tools and need to suppress warnings about mismatched sizes. Verilog implicitly pads or truncates expressions to the appropriate width.
if(CLEAR)
begin
CODE <= 0;
CODEreg <= 0;
end
SystemVerilog has a fill literal '0
, '1
, 'z
that automatically replicates the value to the target expression
if(CLEAR)
begin
CODE <= '0;
CODEreg <= '1;
end