Bit slicing in verilog

20.4k views Asked by At

How can I write wdata[((8*j)+7) : (8*i)] = $random; in verilog programming language? , where i and j are reg type variable. Modelsim gives error for constant range variable. How could I write it in proper manner.

2

There are 2 answers

0
Karan Shah On BEST ANSWER

You should think from Hardware prospective for the solution.

Here is one solution. Hope that it will help you.

module temp(clk);
  input clk;
  reg i, j;
  reg [23:0] register, select;
  wire [23:0] temp;

  initial 
  begin
      i = 'd1;
      j = 'd1;
  end

  generate
  for(genvar i = 0; i<24; i++)
  begin
      assign temp[i] = select[i] ? $random : register[i]; 
  end
  endgenerate

  always @ (posedge clk)
  begin
      register <= temp;
  end

  always @ *
  begin
      select = (32'hffff_ffff << ((j<<3)+8)) ^ (32'hffff_ffff << (i<<3));
  end
endmodule
0
anthrazithe On

Use the array slicing construction. You can find more detailed explanation at Array slicing Q&A

bit [7:0] PA, PB;
int loc;

initial begin
  loc = 3;
  PA = PB;                      // Read/Write
  PA[7:4] = 'hA;                // Read/Write of a slice
  PA[loc -:4] = PA[loc+1 +:4];  // Read/Write of a variable slice equivalent to PA[3:0] = PA[7:4];
end

Verilog 2001 Syntax

[M -: N]  // negative offset from bit index M, N bit result 
[M +: N]  // positive offset from bit index M, N bit result