1

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.

Russell
  • 3,384
  • 4
  • 31
  • 45
  • Can you tell us more about your application? For example, do you have source code control of the application that will be reading the file? If padding the last set of bytes still won't work, you can build a DPI/PLI application that can write a byte at a time. If performance is an issue, you'll still want to use 4 byte or larger buffers until you reach the last few bytes. – dolphus333 Mar 14 '16 at 15:20

2 Answers2

2

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
Greg
  • 18,111
  • 5
  • 46
  • 68
dave_59
  • 39,096
  • 3
  • 24
  • 63
2

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.

TheSVchaos
  • 31
  • 6