Search code examples
verilog

Set a variable number of bits in a signal


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.


Solution

  • 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;