0

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
4
  • I got a possible solution. I can use the property -a mod b = b-(a mod b) where a and b are positive numbers. I can check the MSB to detect negative numbers. Commented Jan 29, 2022 at 13:36
  • in both, general programming and verilog -4 % 5 == -4. So, your question makes no sense. Please provide a code sample where it shows 2 in verilog. Commented Jan 29, 2022 at 13:38
  • @Serge You can try doing -4%5 on python. The answer will be 1. While dealing in modular arithmetic as well, we need the answer to be 1. I will edit my question to include the code where Verilog produces 2 as the answer to this. Commented Jan 29, 2022 at 16:09
  • 1
    @GauthamKrishna, Python has no unsigned variables unless you use a class packaged in something like numpy. In verilog all bit level types are unsigned and you have make an effort to declare things signed and keep expressions signed by not mixing them with unsigned expressions. Commented Jan 29, 2022 at 17:53

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

what is the difference between -4'd4 and 4'd-4?
the second one (4'd-4) is syntactically incorrect and will not compile.
1

You didn’t declare the variables as signed, so they are treated as unsigned. -4’d4 is being interpreted as it’s 2’s complement 4’b12 (~4’b0100 + 1’b1 == 4’b1100)

You need to add the signed keyword to the signal definition.

module test;

wire signed [3:0] a,b,c;

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

endmodule

4 Comments

Is the signed keyword synthesizable?
@GauthamKrishna Yes. Signed keyword is synthesizable. And also system function $signed() is synthesizable.
@Greg what is the difference between -4'd4 and 4'd-4?
signed is synthesizable. modulo(%) is usually not.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.