有时候在项目中需要在SystemVerilog中读取或者写入二进制文件,今天就分享两段代码供大家直接使用。
function void writing_binary_file(int unsigned total_bytes_to_write=32);
int fwrite;
bit [7:0] wdata;
//Open file with binary write mode("wb"), b here specifies binary
fwrite=$fopen("binary_file.bin","wb");
if(fwrite==0)
`uvm_error("NO_FILE_FOUND","Couldn't open file binary_file.bin for writing")
//iterate until all intended bytes are written
for(int i=0,i<total_bytes_to_write,i++) begin
//generate current random byte to write
wdata=$urandom_range(0,255);
//fwrite with %c writes only 1 byte at a time, use "%u" format for writing 32bit data
$fwrite(fwrite,"%c",wdata);//Note that fwrite doesn't introduce newline character unless added with \n
end
//close the file
$fclose(fwrite)
endfunction
function void read_binary_file();
int fread;
bit [7:0] rdata;
int unsigned line_count;
line_count=0;
//Open file with binary read mode("rb"), b here specifies binary
fread=$fopen("binary_file.bin","rb");
if(fread==0)
`uvm_error("NO_FILE_FOUND","Couldn't open file binary_file.bin for reading")
//read until end of file is reached
while(!$feof(fread)) begin
//fgets reads one line at once and $fgetc reads a byte (a character) at once
$fgets(rdata,fread);
line_count+=1;
//Do what's required of data here
`uvm_info(get_name(),$sformatf("byte number %0d, Value= %08x",line_count,rdata),UVM_MEDIUM)
end
//close the opened binary file
$fclose(fread)
endfunction
4.欢迎关注微信公众号《芯片验证日记》
5.欢迎加入知识星球《数字芯片前端验证》
另外,由于微信群已经超过200人,添加小编的微信,拉你进入WX学习群。