How to take variable in array index?

module top;
  int payload_width = 294;
  int test = 0;
  bit [320:0]temp_tlp;
  int small_code;
  initial begin
    temp_tlp = $random;
    small_code = temp_tlp[payload_width-26 :0];
    $display("small_code=%0d",small_code);
  end
endmodule

In this example, I want to assign only some bits of temp_tlp to some other variable, but that some bits are not fixed i.e it’s variable. How can I do this?

In reply to njoshi:

You can create a mask:

module top;
  int payload_width = 294;
  int test = 0;
  bit [320:0]temp_tlp;
  int small_code;
  var type(temp_tlp) mask; // create a variable mask the same type as temp_tlp

  initial begin
    void'(randomize(temp_tlp)); // $random only generates a 32-bit number
    mask = (1'b1 << payload_width) -1;
    small_code = temp_tlp & mask; // bitwise-and
    $display("small_code=%0d",small_code);
  end
endmodule

Note that there is no need to mask a value to fit into a smaller variable. Verilog will silently truncate it.