So I tried to do a program that does the modulo. I couldn't do so.
I tried using idiv
or div
but I just couldn't think off a way to do so. I will really appreciate if you can show me how to perform the modulo operation.
Asked
Active
Viewed 160 times
-4

Sep Roland
- 33,889
- 7
- 43
- 76

bet bet
- 1
1 Answers
3
Modulo operator is % or \ in most assemblers. The modulo operation represents the remainder after dividend is integer-divided by divisor.
For instance when dividend is 13
and divisor is 5
, then the modulo result is 13 % 5 = 3
. Unsigned division is provided in x86 by the instruction DIV and it depends on CPU mode:
; 8bit, works with dividend 0 .. (2^16 - 1) 64 KiB
MOV AX, 13 ; dividend
MOV CL, 5 ; divisor
DIV CL ; Remainder 3 is now in AH, quotient 2 is in AL.
; 16bit, works with dividend 0 .. (2^32 - 1) 4 GiB
MOV AX, 13 ; lower 16 bits of dividend
MOV DX, 0 ; higher 16 bits of dividend
MOV CX, 5 ; divisor
DIV CX ; Remainder 3 is now in DX, quotient 2 is in AX.
; 32bit, works with dividend 0 .. (2^64 - 1) 16 EiB
MOV EAX, 13 ; lower 32 bits of dividend
MOV EDX, 0 ; higher 32 bits of dividend
MOV ECX, 5 ; divisor
DIV ECX ; Remainder 3 is now in EDX, quotient 2 is in EAX.
; 64bit, works with dividend 0 .. (2^128 - 1) 256 ???
MOV RAX, 13 ; lower 64 bits of dividend
MOV RDX, 0 ; higher 64 bits of dividend
MOV RCX, 5 ; divisor
DIV RCX ; Remainder 3 is now in RDX, quotient 2 is in RAX.
It is rather more complicated with signed numbers using signed division IDIV, see the article Modulo on Wikipedia.

Sep Roland
- 33,889
- 7
- 43
- 76

vitsoft
- 5,515
- 1
- 18
- 31
-
2Just to be clear, `idiv` gives you the signed remainder just as easily, with `cdq` / `idiv` for 32-bit operand size for example (*[When and why do we sign extend and use cdq with mul/div?](https://stackoverflow.com/q/36464879)*). But if you want modulo in the sense of Euclidean or floored division, not truncating (quotient rounds toward zero) where `-1 % 2 == -1`, then you'd want more instructions. – Peter Cordes Dec 10 '22 at 18:33
-
2Following up on @PeterCordes comment, remainder is zero or has the same sign as dividend. Mathematical modulo is zero or has the same sign as the divisor. – rcgldr Dec 10 '22 at 18:59
-
Right, but a lot of people misuse the terminology and are fine with remainder. It's worth at least mentioning that remainder is easy, because a lot of people would search on "modulo" for an operation like the C `%` operator. (Of course, people should just ask a compiler if it's something C can do directly. https://godbolt.org/z/YKhvT3jGn – Peter Cordes Dec 10 '22 at 19:11
-
1Just a tip, if you have to do modulo 2 (or some power of 2), just AND with that power of 2 minus 1. So for example, `n % 2` is the same as `n & 1`, `n % 4` is the same as `n & 3`, etc. Not only do you get the same result with `and`, it's also much faster. Unfortunately it only works with powers of 2. – puppydrum64 Dec 12 '22 at 17:32