Search code examples
veriloghdl

Applying Modulo To a Negative Number In Verilog


In general math and software programming, -4 mod 5 = 1. But in Verilog, the answer turns out to be 2. The reason for this seems to be because of division happening in binary. How do I properly handle this calculation? Following is a Verilog code that reproduces this behaviour.

module test (a,b,c);

input [0:3]a,b;
output [0:3]c;

assign a = -4'd4;
assign b = 4'd5;
assign c = a%b;

endmodule

Solution

  • Your code does % operation on unsigned data. In this scheme -4 is just the same as 12 unsigned and the result of modulo is 2.

    You need to use signed data as in here:

    module test (
    input signed [0:3]a,b, // <<<< signed
    output signed [0:3]c   // <<<< signed
    ):
    assign a = -4'd4;
    assign b = 4'd5;
    assign c = a%b;
    
    always @*
      $display(a,b,c);
      
    endmodule
    

    And the result is -4, as expected from general programming rules.