Search code examples
ioverilogfwritefreadnegative-number

read and write in verilog when having negative numbers and array


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

Solution

  • 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