read and write in verilog when having negative num

2019-08-29 01:42发布

问题:

I am now doing reading input data from txt file and write the results into txt file.

However the results runs in the simulation works well but it fail to link back the the conv module which is o = a+b; the system able to read the values in x.txt and d.txt but cannot link it back to a and b. What is my mistake and how to correct it?

And from the same cases in i found out that the system cannot write out negative decimal value although it is change to "%d\n" in $fwrite. Any method to solve that? Should i use $dumpfile to get negative number as output??

Here is the content in d.txt

56
272
1
-62
75

Content in x.txt

562
2723
14
-620
751

Here is my module code:

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

assign o = a + b;
endmodule

My testbench code:

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

回答1:

An example for writing signed number to a text file using 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

Which generates :

      3
      2
      1
      0
     -1
     -2


回答2:

An alternative method to solve your issue is to use a hex value input as shown, convert all negative values to corresponding hex value in the text file explicitly is required

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