Set a variable number of bits in a signal

Viewed 46

I have a module with input, output such as:

input [2:0] start;
input [2:0] range;
input [4:0] sig_in; 
output [4:0] sig_out;

I want to set some bits of signal sig_in. For example, 2 bits from bit 2 to bit 4. How can do it in Verilog? We can't use "not a constant value" in a for loop.

Let me give an example:

initial 
sig_in = 5'b00000;
start = 3'b2;
range = 3'b2;

Expected output:

sig_out = 5'b01100;

Using generate and for loop.

2 Answers

There is no need for a generate construct. Use a for loop to loop through all the bits of the output and set any bits that are inside the desired range.

module dut (
    input [2:0] start,
    input [2:0] range,
    input [4:0] sig_in,
    output reg [4:0] sig_out
);

integer i;
always @* begin
    sig_out = sig_in;
    for (i=0; i<5; i=i+1) begin
        if ((i >= start) && (i < (start+range))) begin
           sig_out[i] = 1; 
        end
    end
end

endmodule

You can do it without any loop at all:

  always_comb 
    sig_out = ((5'b1 << range) - 1'b1) << start;

(5'b1 << range) - 1 creates a mask for the 'range bits', i.e. 00011 for two bits. you only need to shift it left by 'start' bits.

This relates it to signal_in as in your example:

  always_comb 
    sig_out = (((5'b1 << range) - 1'b1) << start) | signal_in;
Related