在SV中读取和写入二进制文件

文摘   2024-06-07 23:02   上海  

错的每一道题都是为了遇见对的人,
而对的每一道题,是为了遇见更好的自己。
--致参加高考的莘莘学子
1.前言

有时候在项目中需要在SystemVerilog中读取或者写入二进制文件,今天就分享两段代码供大家直接使用。

2.write_binary_file.sv
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
3. read_binary_file.sv
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.欢迎加入知识星球《数字芯片前端验证》

一切改变源于看见;
看,是一种本能;
看见,是一种学问。
欢迎加入知识星球。星球内每周都有高质量内容更新!每天都会解答大家提出的技术问题。欢迎加入知识星球,助您快速成长。
最后,由于TX修改规则,为了不错过后续内容,欢迎加入QQ群,

另外,由于微信群已经超过200人,添加小编的微信,拉你进入WX学习群。

感谢关注微信公众号《芯片验证日记》,
一起好好学习,天天向上!

芯片验证日记
分享芯片验证相关的知识。
 最新文章