当有负数和数组时,用verilog读写

时间:2015-03-16 09:27:08

标签: io verilog fwrite fread negative-number

我现在正在从txt文件中读取输入数据并将结果写入txt文件。

然而,在模拟中运行的结果很好但是它无法链接回转模块,即o = a + b;系统能够读取x.txt和d.txt中的值,但无法将其链接回a和b。我的错误是什么?如何纠正?

从我发现的相同情况中,虽然在$ fwrite中将系统更改为“%d \ n”,但系统无法写出负十进制值。任何解决方法?我应该使用$ dumpfile来获取负数作为输出吗?

以下是d.txt

中的内容
56
272
1
-62
75

x.txt中的内容

562
2723
14
-620
751

这是我的模块代码:

module conv (input signed[15:0]a,b,
         output signed[15:0] o);

assign o = a + b;
endmodule

我的测试平台代码:

module conv_tb();

reg clk;
reg signed [15:0]a[4:0];
reg signed [15:0]b[4:0];
wire signed [15:0]o[4:0];

integer ai,bi,oo,i;

conv U1(.a(a),.b(b),.o(o));

initial begin
    clk <= 1'b0;
    forever
    #1 clk = ~clk;
end

initial begin
   ai = $fopen("x.txt","r");
   bi = $fopen("d.txt","r");
   oo = $fopen("o.txt","w");
   #1;
   for (i = 0; i<5; i=i+1)
       a <= $fscanf(ai,"%d\n",x);
       b <= $fscanf(bi,"%d\n",d);
       #4;
       $fwrite(oo,"%d\n",o);
   end
   $fclose(ai);
   $fclose(bi);
   $fclose(oo);
   $finish;
   end
endmodule

2 个答案:

答案 0 :(得分:0)

解决您的问题的另一种方法是使用如图所示的十六进制值输入,明确地将所有负值转换为文本文件中对应的十六进制值

module conv ( input signed [15:0] a, b,
              output signed [15:0] o);
  assign o = a + b;
endmodule

module conv_tb(); 
reg signed [15:0] a,b,o;
conv u0(.a(a),.b(b),.o(o));

reg [15:0] Mem [0:4]; 
reg [15:0] Mem1 [0:4]; 
integer j,k,oo; 

initial
begin 
  $readmemh("x.txt",Mem); 
  $readmemh("d.txt",Mem1); 
  oo = $fopen("o.txt","w");
end

initial begin 
  for (k=0; k<5; k=k+1) begin a= Mem[k]; end
  for (j=0; j<5; j=j+1) begin b= Mem1[j]; $fwrite(oo,"%d\n",o); end
end 
endmodule

答案 1 :(得分:0)

使用fwrite将签名号码写入文本文件的示例:

module write_signed;
integer out_file;
initial begin
   out_file = $fopen("out_file.txt","w");
   $fwrite(out_file, "%d\n", 3);
   $fwrite(out_file, "%d\n", 2);
   $fwrite(out_file, "%d\n", 1);
   $fwrite(out_file, "%d\n", 0);
   $fwrite(out_file, "%d\n", -1);
   $fwrite(out_file, "%d\n", -2);
   $fclose(out_file);
end

endmodule

生成:

      3
      2
      1
      0
     -1
     -2