Assembly Language – How to do Modulo?

If your modulus / divisor is a known constant, and you care about performance, see this and this. A multiplicative inverse is even possible for loop-invariant values that aren’t known until runtime, e.g. see https://libdivide.com/ (But without JIT code-gen, that’s less efficient than hard-coding just the steps necessary for one constant.) Never use div for known powers of 2: it’s much slower than and for remainder, … Read more

When and why do we sign extend and use cdq with mul/div?

Use cdq / idiv for signed 32-bit / 32-bit => 32 bit division,xor edx,edx / div for unsigned. With the dividend in EAX to start with, and the divisor specified as an operand to DIV or IDIV. If you zero EDX/RDX instead of sign-extending into EDX:EAX before idiv, you can get a large positive result for -5 / 2, for example. Using the “full … Read more

Int division: Why is the result of 1/3 == 0?

The two operands (1 and 3) are integers, therefore integer arithmetic (division here) is used. Declaring the result variable as double just causes an implicit conversion to occur after division. Integer division of course returns the true result of division rounded towards zero. The result of 0.333… is thus rounded down to 0 here. (Note that the processor … Read more

What is the behavior of integer division?

Will result always be the floor of the division? What is the defined behavior? Not quite. It rounds toward 0, rather than flooring. 6.5.5 Multiplicative operators 6 When integers are divided, the result of the / operator is the algebraic quotient with any fractional part discarded.88) If the quotient a/b is representable, the expression (a/b)*b … Read more