Search code examples
simulationsystem-verilogtest-bench

Assign darray of ints to darray of a custom type


Given dynamic array (darray) of ints (32-bit), the intent is to assign each array element to the elements of a drray of a custom type which is a darray of 8 bit vectors.
Have tried three methods, each errors differently.
I placed the error message in the code as a comment near the line which causes the error.
Method 1:

module tb ();
  
int my_ints [];
typedef bit [7 :0] my_type [];
my_type my_array [];

  initial begin
    my_ints  = new[2];
    my_array = new[2];
    //
    my_ints = '{1,2};
    
    // *E,TYCMPAT (testbench.sv,15|26): assignment operator type check failed 
    // (expecting datatype compatible with 
    // 'tb::my_type (dynamic array of packed array [7:0] of bit)' 
    // but found 'int' instead)
    foreach(my_ints[i]) begin
      my_array[i] = my_ints[i];
      $display("my_array[0] = %d",my_array[0]);
    end

  end
endmodule

Method 2:

module tb ();
  
int my_ints [];
typedef bit [7 :0] my_type [];
my_type my_array [];

  initial begin
    my_ints  = new[2];
    my_array = new[2];
    
    my_ints = '{1,2};
    
    // *E,WOUPXR (./testbench.sv,16|41): An expression with an unpacked array datatype 
    // is not allowed in this context [SystemVerilog].
    foreach(my_ints[i]) begin
      my_array[i] = my_type'(my_ints[i]);
      $display("my_array[0] = %d",my_array[0]);
    end

  end
endmodule    

Method 3:

module tb ();
  
int my_ints [];
typedef bit [7 :0] my_type [];
my_type my_array [];
  
  initial begin
    my_ints  = new[2];
    my_array = new[2];
    
    my_ints = '{1,2};
    
    // *E,TYCMPAT (testbench.sv,15|26): assignment operator type check failed 
    // (expecting datatype compatible with 'tb::my_type 
    // (dynamic array of packed array [7:0] of bit)' but found 'packed array' instead).
    foreach(my_ints[i]) begin
      my_array[i] = my_ints[i][7:0];
      $display("my_array = %d",my_array[i]);
    end

  end
endmodule    

How can a darry of ints be assigned element by element to a darry of a custom type of 8-bit vectors?
Just want the low 8 bits of the int (the natural Verilog chopping of assigning a larger vector to a smaller vector).


Solution

  • In all cases your 'my_array' is a 3-dimensional array with two undefined dimensions. typedef bit [7 :0] my_type []; defines my_type as a two-dimensional array. my_type my_array []; defines an array of two-dimensional arrays --> a 3-dimensional array.

    As a result, neither of your assignment works in any of the methods.

    Method 1 would work if you either remove the last [] in typedef or from declaration: my_type my_array;.

    Method 2 will never work, since your casting is incompatible in any case.

    Method 3 is similar to the method 1.