-->

verilog fwrite output bytes

2019-09-07 05:26发布

问题:

I know that if I am outputting a binary file in verilog, then I can use the following verilog IO standard function:

$fwrite(fd,"%u",32'hABCDE124); 

But the above command writes 4-byte data into the file. What if the binary data that I want to write is only one-byte, two-bytes or three-bytes? How can I do this?

For example, I know the following won't do what I want:

$fwrite(fd,"%u",8'h24);
$fwrite(fd,"%u",16'hE124);
$fwrite(fd,"%u",24'hCDE124);

Is there any way that I can write a non 4-byte multiple data into a file?

Thanks,

--Rudy

回答1:

You can use %c to write out a single byte. You can use a bit-stream cast to convert your data into an array of bytes, then do

foreach(array_of_bytes[i]) $fwrite(fd,"%c",array_of_bytes[i]);

If you have a large amount of data, you may want to optimize this by writing out the multiple of 4-bytes with %u, and the remaining bytes with `%c'.



回答2:

You can use %s instead of %u:

$fwrite(fd_s,"%s",8'h24);
$fwrite(fd_s,"%s",16'hE124);
$fwrite(fd_s,"%s",24'hCDE124);   

https://www.edaplayground.com/x/4vJn



回答3:

I suggest another version of dave_59's answer. The key is using multiple %c.

wire [7:0] byte;
wire [15:0] two_bytes;
wire [23:0] three_bytes;
----
assign byte = 8'h24;
assign two_bytes = 16'hE124;
assign three_bytes = 24'hCDE124;
----
$fwrite(fd_s,"%c",byte);
$fwrite(fd_s,"%c%c",two_bytes[15-:8],two_bytes[7-:8]);
$fwrite(fd_s,"%c%c%c",three_bytes[23-:8],three_bytes[15-:8],three_bytes[7-:8]);

When using %u - be aware of Your system byte ordering, it uses native by default.