首页 文章

VHDL中mod和rem运算符的区别?

提问于
浏览
10

我在VHDL编程中遇到了这些语句,无法理解两个运算符mod和rem之间的区别

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

2 回答

  • 24

    一种看待不同的方法是在测试平台上运行快速模拟,例如使用如下过程:

    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;
    

    它显示结果:

    # ** 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有详尽的描述,包括规则:

    • mod有除数的符号,因此在 a mod nn

    • rem有分红的迹象,因此 aa rem n

    mod 运算符给出一个向下舍入的除法(浮动除法)的残差,所以 a = floor_div(a, n) * n + (a mod n) . 优点是 a mod n 是一个重复的锯齿图,当 a 甚至通过零增加时,这在某些计算中很重要 .

    rem 运算符给出了常数整数除法 a / n 的余数,它朝向0(截断除法)舍入,因此 a = (a / n) * n + (a rem n) .

  • 0
    For equal sign:
    9/5=-9/-5=1.8 gets 1 
    9 mod 5 = 9 rem 5
    -9 mod -5 = -9 rem -5
    -----------------------------------------
    For unequal signs:
    9/-5 = -9/5 = -1.8
    In "mod" operator : -1.8 gets -2
    In "rem" operator : -1.8 gets -1
    ----------------------------------------
    example1: (9,-5)
    9 = (-5*-2)-1  then:  (9 mod -5) = -1
    9 = (-5*-1)+4  then:  (9 rem -5) = +4
    ----------------------------------------
    example2: (-9,5)
    -9 = (5*-2)+1  then:  (-9 mod 5) = +1
    -9 = (5*-1)-4  then:  (-9 rem 5) = -4
    ----------------------------------------
    example3: (-9,-5)
    -9 = (-5*1)-4  then:  (-9 mod -5) = -4
    -9 = (-5*1)-4  then:  (-9 rem -5) = -4
    ----------------------------------------
    example4: (9,5)
    9 = (5*1)+4  then:  (9 mod 5) = +4
    9 = (5*1)+4  then:  (9 rem 5) = +4
    

相关问题