将值 0 写入二进制文件
我正在从 SystemVerilog 模拟环境生成一个二进制文件。目前,我正在执行以下操作:
module main;
byte arr[] = {0,32, 65, 66, 67};
initial begin
int fh=$fopen("/home/hagain/tmp/h.bin","w");
for (int idx=0; idx<arr.size; idx++) begin //{
$fwrite(fh, "%0s", arr[idx]);
end //}
$fclose(fh);
$system("xxd /home/hagain/tmp/h.bin | tee /home/hagain/tmp/h.txt");
end
endmodule : main
问题是,当 b 的值为 0 时,不会向文件写入任何内容。 xxd 输出是:
0000000: 2041 4243 ABC
转换为字符串时的结果如下:
$fwrite(fh, string'(arr[idx]));
我尝试将写入命令更改为:
$fwrite(fh, $sformatf("%0c", arr[idx]));
然后前两个字节('d0 和 'd32)得到相同的值:
0000000: 2020 4142 43 ABC
关于如何生成此二进制文件的任何想法文件?
I am generating a binary file from a SystemVerilog simulation environment. Currently, I'm doing the following:
module main;
byte arr[] = {0,32, 65, 66, 67};
initial begin
int fh=$fopen("/home/hagain/tmp/h.bin","w");
for (int idx=0; idx<arr.size; idx++) begin //{
$fwrite(fh, "%0s", arr[idx]);
end //}
$fclose(fh);
$system("xxd /home/hagain/tmp/h.bin | tee /home/hagain/tmp/h.txt");
end
endmodule : main
The problem is, that when b has the value of 0, nothing is written to the file. xxd output is:
0000000: 2041 4243 ABC
Same result when casting to string as follows:
$fwrite(fh, string'(arr[idx]));
I tried to change the write command to:
$fwrite(fh, $sformatf("%0c", arr[idx]));
And then I got the same value for the first two bytes ('d0 and 'd32):
0000000: 2020 4142 43 ABC
Any idea on how to generate this binary file?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
字符串中间不能有 null(0) 字符,它用于终止字符串。
您应该对 u 信息数据使用
%u
格式说明符。请注意,%u 以最低有效字节优先的顺序写入 32 位值,因此我反转了使用流运算符写入的字节
{<<8{arr[idx+:4]}}
。如果字节数不能被 4 整除,它只会用空字节填充文件。如果您需要确切的字节数,则必须使用一些 DPI C 代码
,然后使用以下命令导入它
You cannot have a null(0) character in the middle of a string, it is used to terminate the string.
You should use the
%u
format specifier for unformated data.Note that %u writes a 32-bit value in least-significant bytes first order, so I reversed the bytes being written with the streaming operator
{<<8{arr[idx+:4]}}
. If the number of bytes is not divisible by 4, it will just pad the file with null bytes.If you need the exact number of bytes, the you will have to use some DPI C code
And then import it with