# Reading a file in Verilog

I want to read a file in Verilog that contains both positive and negative numbers. For example, the file contents are:

-4
20
28
-52


and so on.

Also, after reading I have to multiply these numbers with a signal. I'm confused how to read these numbers.

One approach is to use $readmemb() directive, but it requires numbers in binary format. That can be done easily, but what about the negative numbers, in which format does Verilog accept negative numbers, 1's complement, 2's complement or signed MSB format? ## 2 Answers To read integer values (positive and negative) in decimal format, you can use the $fscanf system function. Refer to IEEE Std 1800-2017, section 21.3 File input/output system tasks and system functions.

module tb;

int fd, data;

initial begin
fd = $fopen("data.txt", "r"); while (!$feof(fd)) begin
void'($fscanf(fd, "%d\n", data));$display("%0d", data);
end
end

endmodule


This prints:

-4
20
28
-52


Table 21-8 \$fscanf input field characters, format %d states:

Matches an optionally signed decimal number, consisting of the optional sign from the set + or –, followed by a sequence of characters from the set 0,1,2,3,4,5,6,7,8,9, and _, ...

I chose the type int for convenience, but you can choose any signed integer type that suits you.

By default, signed numbers in Verilog use a 2's-complement representation. However, you can use whatever representation you like as long as you write your own math operators.