0

I am trying to read in a hex file that is n lines long, with each line consisting of a 32-bit hex value. I then need to take the 32-bit hex values and turn them into 8-bit bytes to be used in a memory model.

I am able to open the file and loop through it to extract each value in a line and see that I am reading each line correctly with this loop:

fd = $fopen("test.dat", "r");
        if(fd)
            begin
                $display("Reading file %0d", fd);

                for(int i=0; i<num_lines; i++)
                    begin
                        $fscanf(fd, "%h", line[i]); 
                        $display("line: %h", line[i]);
                end
         end

I get a console output when running my test bench of

line: 00000000
line: 00000001
line: 00000002
line: 00000003
line: 00000004
line: 00000005
line: 00000006
line: 00000007
line: 00000008
line: 00000009
line: 0000000a
line: 0000000b
line: 0000000c
line: 0000000d
line: 0000000e
line: 0000000f
line: 00000010
line: 00000011
line: ffffffff

which is what I expect.

I am having trouble splitting these values into four 8-bit bytes each. I want the first line to be split into 00 00 00 00 the second to be 00 00 00 01 and so on. I need to save the bytes in its own variable to be looped through and inserted into a memory model for test benching.

toolic
  • 57,801
  • 17
  • 75
  • 117
rt0218
  • 1

1 Answers1

0

Assuming line is declared something like a "memory" variable, you can use indexed part-select to separate the 32-bit value into 4 bytes:

module tb;

reg [31:0] line [0:18];

initial begin
    $readmemh("test.dat", line);
    for (int i=0; i<19; i++) begin
        $write("line='h%08x : ", line[i]);
        for (int j=3; j>=0; j--) begin
            $write("%02x ", line[i][8*j +: 8]);
        end
        $display;
    end
end

endmodule

Prints:

line='h00000000 : 00 00 00 00 
line='h00000001 : 00 00 00 01 
line='h00000002 : 00 00 00 02 
line='h00000003 : 00 00 00 03 
line='h00000004 : 00 00 00 04 
line='h00000005 : 00 00 00 05 
line='h00000006 : 00 00 00 06 
line='h00000007 : 00 00 00 07 
line='h00000008 : 00 00 00 08 
line='h00000009 : 00 00 00 09 
line='h0000000a : 00 00 00 0a 
line='h0000000b : 00 00 00 0b 
line='h0000000c : 00 00 00 0c 
line='h0000000d : 00 00 00 0d 
line='h0000000e : 00 00 00 0e 
line='h0000000f : 00 00 00 0f 
line='h00000010 : 00 00 00 10 
line='h00000011 : 00 00 00 11 
line='hffffffff : ff ff ff ff 
toolic
  • 57,801
  • 17
  • 75
  • 117