ssgr
ssgr

Reputation: 389

Reading of hex file in testbench : Verilog

I have converted an image file into hex file which has R,G,B and alpha values in multiple columns. For example :

3c 48 36 ff 1d 2b 19 ff 08 18 06 ff 08 17 05 ff
14 1f 0d ff 1b 22 11 ff 1a 1f 0e ff 1a 1b 0b ff
1d 1a 0b ff 20 1a 0b ff 23 1a 0c ff 23 1c 0d ff
24 1d 0e ff 24 1d 0e ff 21 1c 0d ff 23 1c 0d ff
1f 1a 0b ff 1e 19 0a ff 1c 19 0a ff 1e 1a 0b ff
20 1a 0b ff 24 18 0b ff 23 18 0a ff 21 18 0a ff

Now I want a way to read and store this data as a collection of 32 bits( i.e. 4bytes). If I do not know how bytes are present in the file (since file can be of any size), how can I achieve this?

Upvotes: 1

Views: 6067

Answers (1)

Unn
Unn

Reputation: 5098

If you have a file in that given format, you can use the $readmemh system call to take those values and put them in a Verilog array:

localparam MAX_SIZE 1024 /* Set this to the maxium image size in bytes */

reg [7:0] image_8[MAX_SIZE-1:0];
reg [31:0] image_32[(MAX_SIZE/4)-1:0];
integer i;

initial begin
  $readmemh("file.hex", image);
  for (i = 0; i < MAX_SIZE/4; i = i + 1) begin
    image_32[i] = ({24'b0, image_8[i*4]} << 24) | ({24'b0, image_8[i*4 + 1]} << 16) | ({24'b0, image_8[i*4 + 2]} << 8) | (image_8[i*4 + 3]);
  end
end

That should get you your image as a Verilog array, with each element being 32-bits long.

(Note that smaller files will leave a bunch of 'x values in the array, so you can check for this to determine length if needed)

Upvotes: 1

Related Questions