Difference between mod and rem operators in VHDL?

musicakc picture musicakc · Sep 15, 2014 · Viewed 70.9k times · Source

I came across these statements in VHDL programming and could not understand the difference between the two operators mod and rem

    9 mod 5
    (-9) mod 5
    9 mod (-5)
    9 rem 5
    (-9) rem 5
    9 rem (-5)

Answer

Morten Zilmer picture Morten Zilmer · Sep 15, 2014

A way to see the different is to run a quick simulation in a test bench, for example using a process like this:

process is
begin
  report "  9  mod   5  = " & integer'image(9 mod 5);
  report "  9  rem   5  = " & integer'image(9 rem 5);
  report "  9  mod (-5) = " & integer'image(9 mod (-5));
  report "  9  rem (-5) = " & integer'image(9 rem (-5));
  report "(-9) mod   5  = " & integer'image((-9) mod 5);
  report "(-9) rem   5  = " & integer'image((-9) rem 5);
  report "(-9) mod (-5) = " & integer'image((-9) mod (-5));
  report "(-9) rem (-5) = " & integer'image((-9) rem (-5));
  wait;
end process;

It shows the result to be:

# ** Note:   9  mod   5  =  4
# ** Note:   9  rem   5  =  4
# ** Note:   9  mod (-5) = -1
# ** Note:   9  rem (-5) =  4
# ** Note: (-9) mod   5  =  1
# ** Note: (-9) rem   5  = -4
# ** Note: (-9) mod (-5) = -4
# ** Note: (-9) rem (-5) = -4

Wikipedia - Modulo operation has an elaborate description, including the rules:

  • mod has sign of divisor, thus n in a mod n
  • rem has sign of dividend, thus a in a rem n

The mod operator gives the residue for a division that rounds down (floored division), so a = floor_div(a, n) * n + (a mod n). The advantage is that a mod n is a repeated sawtooth graph when a is increasing even through zero, which is important in some calculations.

The rem operator gives the remainder for the regular integer division a / n that rounds towards 0 (truncated division), so a = (a / n) * n + (a rem n).