Russell
Russell

Reputation: 3457

Write one byte at a time to a binary file in SystemVerilog

I want to write a binary file (meaning that it needs to be opened in a hex editor). I want to write one byte at a time in SystemVerilog. I currently am only able to write 32-bits (4 bytes) at a time. This does not work for me. Here's the code I'm working with:

task t_Write_File(input string i_File_Name);
  int n_File_ID;
  n_File_ID = $fopen(i_File_Name, "wb");
  for (int i=0; i<n_Active_Rows; i++)
  begin
    for (int j=0; j<n_Active_Cols; j++)
    begin
        $fwrite(n_File_ID, "%u", r_Frame[i][j]);
    end
  end
  $fclose(n_File_ID);
endtask : t_Write_File

The problem here is that r_Frame is bytes, so it pads the heck out of the data (out to 32-bits). I do not want padding.

Upvotes: 1

Views: 4264

Answers (2)

TheSVchaos
TheSVchaos

Reputation: 31

Just use "%c" instead of "%u", like

for (int j=0; j<n_Active_Cols; j++)
begin
    $fwrite(n_File_ID, "%c", r_Frame[i][j]);
end

The answer was adapted from here.

Upvotes: 2

dave_59
dave_59

Reputation: 42673

You are going need to pack your bytes into 32-bit units(4 bytes). You can do that inside your inner most for-loop

task t_Write_File(input string i_File_Name);
  int n_File_ID;
  bit [32:0] buffer;
  int index;
  n_File_ID = $fopen(i_File_Name, "wb");
  for (int i=0; i<n_Active_Rows; i++)
  begin
    for (int j=0; j<n_Active_Cols; j++)
    begin
        buffer[8*(index++) +:8] = r_Frame[i][j];
        if (index == 4) begin
            index = 0;
            $fwrite(n_File_ID, "%u", buffer);
        end
    end
  end
  $fclose(n_File_ID);
endtask : t_Write_File

Upvotes: 2

Related Questions