Is there something like a modulo operator or instruction in x86 assembly?
This question is related to
assembly
x86
modulo
integer-division
If you don't care too much about performance and want to use the straightforward way, you can use either DIV
or IDIV
.
DIV
or IDIV
takes only one operand where it divides
a certain register with this operand, the operand can
be register or memory location only.
When operand is a byte: AL = AL / operand, AH = remainder (modulus).
Ex:
MOV AL,31h ; Al = 31h
DIV BL ; Al (quotient)= 08h, Ah(remainder)= 01h
when operand is a word: AX = (AX) / operand, DX = remainder (modulus).
Ex:
MOV AX,9031h ; Ax = 9031h
DIV BX ; Ax=1808h & Dx(remainder)= 01h
If you compute modulo a power of two, using bitwise AND is simpler and generally faster than performing division. If b
is a power of two, a % b == a & (b - 1)
.
For example, let's take a value in register EAX, modulo 64.
The simplest way would be AND EAX, 63
, because 63 is 111111 in binary.
The masked, higher digits are not of interest to us. Try it out!
Analogically, instead of using MUL or DIV with powers of two, bit-shifting is the way to go. Beware signed integers, though!
An easy way to see what a modulus operator looks like on various architectures is to use the Godbolt Compiler Explorer.
Source: Stackoverflow.com