Reading and writing binary files in VHDL is not straightforward, I am not sure why this is so. I think that Verilog and SystemVerilog are more closer to C. Do they have built in capability to read/write binary files? I would expect SystemVerilog to have it since it is a high level language intended for verification. However, I am not sure about Verilog at all.
-
1\$\begingroup\$ Yes it does. What it doesn't have is any guarantee of portability between simulators, or any files not written by the same simulator, though e.g. with Modelsim (and probably ghdl) it'll work. \$\endgroup\$user16324– user163242018年06月02日 23:15:48 +00:00Commented Jun 2, 2018 at 23:15
-
\$\begingroup\$ so what type do use to read in binary file once I have read into a line, a character? \$\endgroup\$quantum231– quantum2312018年06月03日 17:04:51 +00:00Commented Jun 3, 2018 at 17:04
-
\$\begingroup\$ Funnily enough I just searched "VHDL read binary files" and found this. electronics.stackexchange.com/questions/258964/… and this stackoverflow.com/questions/14173652/… \$\endgroup\$user16324– user163242018年06月03日 21:54:52 +00:00Commented Jun 3, 2018 at 21:54
-
\$\begingroup\$ yes, overworked. \$\endgroup\$quantum231– quantum2312018年06月04日 03:11:26 +00:00Commented Jun 4, 2018 at 3:11
1 Answer 1
I have never tried it so I just opened my little System Verilog Golden Reference Guide for the exact syntax. I found a description of $fopen
but I also found some corrections I made to the text.
$fopen( "filename" , "mode [b] [+] ");
mode can be r (read), w (write), a(append).
b is for binary
the final + is open for read and write.
fd = $fopen("example","rb+");
The following worked for me returning 0x0, 0x01 .. 0xFF from a 256 byte test file:
reg [7:0] binv;
integer fd;
integer loop;
initial
begin
fd = $fopen("C:\\tmp\\hex256.bin","rb");
if (fd==0)
begin
$display("Could not open file '%s'","c:\\tmp\\test.bin");
$stop;
end
for (loop=0; loop<256; loop=loop+1)
begin
binv = $fgetc(fd);
$display("0x%02X",binv);
end
end
I also had a quick test leaving the 'b' out. The reading goes from 0x00..0x19. After that it produces 0xFF. I interpret from that, that 0x1A (Control-Z) is seen as an EOF. However, as that is a Windows/DOS feature, it might well be that on a Unix/Linux system the program would even work in text mode. I would still use "rb" as it makes it compatible and also make clear to other readers of your code, that you are working with binary files