How is the modulo operator (%) actually computed?

前端 未结 2 1315
悲哀的现实
悲哀的现实 2021-02-15 14:24

Recently I\'ve been confused about the modulo operator, %.

It\'s known that a % b == a-a/b*b when we have integers a and b

2条回答
  •  悲&欢浪女
    2021-02-15 15:03

    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 a register.
    http://pdos.csail.mit.edu/6.828/2007/readings/i386/IDIV.htm

提交回复
热议问题