Why is `OUT_MEM_BANK[3] = 101` instead of expected 0x03 in my Verilog bit rearrangement task?

Hi all,

I’m working on a Verilog/SystemVerilog task that rearranges bits from a 312-bit word into a new 312-bit format using 8-bit temporary storage (temp[39]). Below is a simplified version of my code:

`define NUM_OF_BANK_LINES (1024*3)
`define RAM_MODEL_DEPTH 1024

module test;

  reg i_CLK = 0;
  reg [311:0] RAM_BANK_LO[`RAM_MODEL_DEPTH * 3];
  reg [311:0] MY_RAM_BANK_LO[`RAM_MODEL_DEPTH * 3];
  int i, j;

  always #(1.25) i_CLK = ~i_CLK;

  task mem_task(
    input  [311:0] IN_MEM_BANK [`NUM_OF_BANK_LINES],
    output reg [311:0] OUT_MEM_BANK [`NUM_OF_BANK_LINES]
  );
    reg [7:0] temp[39];

    for (int row = 0; row < `NUM_OF_BANK_LINES; row++) begin
      for (int loc = 0; loc < 39; loc++) begin
        temp[loc][0] = IN_MEM_BANK[row][39*0 + loc];
        temp[loc][1] = IN_MEM_BANK[row][39*1 + loc];
        temp[loc][2] = IN_MEM_BANK[row][39*2 + loc];
        temp[loc][3] = IN_MEM_BANK[row][39*3 + loc];
        temp[loc][4] = IN_MEM_BANK[row][39*4 + loc];
        temp[loc][5] = IN_MEM_BANK[row][39*5 + loc];
        temp[loc][6] = IN_MEM_BANK[row][39*6 + loc];
        temp[loc][7] = IN_MEM_BANK[row][39*7 + loc];
      end

      OUT_MEM_BANK[row] = {
        temp[38], temp[37], temp[36], temp[35], temp[34], temp[33],
        temp[32], temp[31], temp[30], temp[29], temp[28], temp[27],
        temp[26], temp[25], temp[24], temp[23], temp[22], temp[21],
        temp[20], temp[19], temp[18], temp[17], temp[16], temp[15],
        temp[14], temp[13], temp[12], temp[11], temp[10], temp[9],
        temp[8],  temp[7],  temp[6],  temp[5],  temp[4],  temp[3],
        temp[2],  temp[1],  temp[0]
      };

      for (j = 0; j < 39; j++)
        $display("temp[%0d] = %0h", j, temp[j]);

      $display("OUT_MEM_BANK[%0d] = %0h", row, OUT_MEM_BANK[row]);
    end
  endtask

  initial begin
    for (i = 0; i < 1000; i++) begin
      RAM_BANK_LO[i] = i;
    end
    mem_task(RAM_BANK_LO, MY_RAM_BANK_LO);
  end

endmodule

The problem:

When temp[0] = 1 and temp[1] = 1, and all other temp[2] to temp[38] are zero, I expect:

OUT_MEM_BANK[3] = 8'b00000011 = 0x03

However, what I actually get is:

OUT_MEM_BANK[3] = 0x65 (decimal 101)

Question:

Why am I seeing OUT_MEM_BANK[3] = 101 instead of 0x03, even though only temp[0] and temp[1] are 1?


Additional Info:

  • OUT_MEM_BANK is a 312-bit vector.
  • It seems like only the LSB of each temp[x] is being assigned, but I’m not explicitly zeroing out upper bits. Could that be the cause?

For helping to understand my problem I attached a link