How is the modulo (%) operator actually calculated?

Recently, I was confused by the modulo operator, % .

It is known that a % b == aa/b*b when we have integers a and b , where a > b , and we can do this calculation manually if a and b are small enough.

However, when it comes to how the processor calculates it, does it use the same method as the previously mentioned, aa/b*b ? Maybe just by translating the division into subtraction or addition, or is there some kind of bias possible?

+8
language-agnostic modulo
source share
2 answers

With the exception of powers of 2, where the modulo operator can (and in most optimizing compilers) turn into a simple bitwise operation, I'm afraid the only way to do this is the hard way. Explanation http://en.wikipedia.org/wiki/Modulo_operation

In another answer, @Henk Holterman indicates that some processors do this in microcode, leaving a remainder in the register when performing integer division, which means that the modulo command can be reduced to integer division and returns the remainder. (I am adding this information here because this answer has already been accepted.)

+8
source share

It uses the idiv assembly instruction :

  int x = a % b; 00000050 cmp dword ptr [rsp+20h],80000000h 00000058 jne 0000000000000061 0000005a cmp dword ptr [rsp+24h],0FFFFFFFFh 0000005f je 0000000000000070 00000061 mov eax,dword ptr [rsp+20h] 00000065 cdq 00000066 idiv eax,dword ptr [rsp+24h] 0000006a mov dword ptr [rsp+2Ch],edx 0000006e jmp 0000000000000075 00000070 call FFFFFFFFF2620E70 00000075 mov eax,dword ptr [rsp+2Ch] 00000079 mov dword ptr [rsp+28h],eax 

idiv stores the remainder in the register.
http://pdos.csail.mit.edu/6.828/2007/readings/i386/IDIV.htm

+5
source share

All Articles