How to declare and use 1D and 2D byte arrays in Verilog?

Ursa Major picture Ursa Major · Jun 10, 2010 · Viewed 193.6k times · Source

How to declare and use 1D and 2D byte arrays in Verilog?

eg. how to do something like

byte a_2D[3][3];
byte a_1D[3];

// using 1D
for (int i=0; i< 3; i++)
{
    a_1D[i] = (byte)i;
}

// using 2D
for (int i=0; i< 3; i++)
{
    for (int j=0; j< 3; j++)
    {
        a_2D[i][j] = (byte)i*j;
    }
}

Answer

Marty picture Marty · Jun 10, 2010

Verilog thinks in bits, so reg [7:0] a[0:3] will give you a 4x8 bit array (=4x1 byte array). You get the first byte out of this with a[0]. The third bit of the 2nd byte is a[1][2].

For a 2D array of bytes, first check your simulator/compiler. Older versions (pre '01, I believe) won't support this. Then reg [7:0] a [0:3] [0:3] will give you a 2D array of bytes. A single bit can be accessed with a[2][0][7] for example.

reg [7:0] a [0:3];
reg [7:0] b [0:3] [0:3];

reg [7:0] c;
reg d;

initial begin

   for (int i=0; i<=3; i++) begin
      a[i] = i[7:0];
   end

   c = a[0];
   d = a[1][2]; 


   // using 2D
   for (int i=0; i<=3; i++)
      for (int j=0; j<=3; j++)
          b[i][j] = i*j;  // watch this if you're building hardware

end