3
\$\begingroup\$

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?

\$\endgroup\$

2 Answers 2

3
\$\begingroup\$

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.

\$\endgroup\$
0
\$\begingroup\$

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.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.