0

What is range of % operator in Verilog? In C I know if I write number%10 then output is between 0 and 9. But I tried in Verilog and result I am getting is between -9 and 9? Why is that?

enter code here
module testbench;
integer i;
reg signed [15:0] a,b;
initial
begin
for(i = 0; i < 9; i = i + 1)
begin
    a= $random%10;
    b= $random%20;  
    $display("A: %d and B : %d",a,b);
end
end
endmodule

1 Answers1

4

Modulus can return negative numbers as clearly stated in Verilog's IEEE Std 1364-2001 § 4.1.5 Arithmetic operators as well as SystemVerilog's IEEE Std 1800-2012 § 11.4.3 Arithmetic operators

The result of a modulus operation shall take the sign of the first operand.

Both LRMs (Language Reference Manual) also give examples.

To guarantee a positive number, you can use $unsigned(). Example:

a = $unsigned($random) % 10;

If you enable SystemVerilog, you can replace $unsigned($random) with $urandom or replace $unsigned($random) % 10 with $urandom_range(9, 0); see IEEE Std 1800-2012 § 18.13 Random number system functions and methods


FYI : C/C++ does the same with negative numbers. Refer to prior answered questions: Modulo operation with negative numbers and Modulo operator with negative values

Greg
  • 18,111
  • 5
  • 46
  • 68