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.

1
  • 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. Commented Mar 14, 2016 at 15:20

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

2 Comments

That's unfortunate, especially if my number of bytes isn't divisible by 4.
That's pretty easy to deal with - just check if index !=0 after the nested for loop and write the remaining buffer.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.