C++ Best way to get integer division and remainder

后端 未结 8 1950
挽巷
挽巷 2020-12-01 00:29

I am just wondering, if I want to divide a by b, and am interested both in the result c and the remainder (e.g. say I have number of seconds and want to split that into minu

8条回答
  •  悲哀的现实
    2020-12-01 01:03

    On x86 at least, g++ 4.6.1 just uses IDIVL and gets both from that single instruction.

    C++ code:

    void foo(int a, int b, int* c, int* d)
    {
      *c = a / b;
      *d = a % b;
    }
    

    x86 code:

    __Z3fooiiPiS_:
    LFB4:
        movq    %rdx, %r8
        movl    %edi, %edx
        movl    %edi, %eax
        sarl    $31, %edx
        idivl   %esi
        movl    %eax, (%r8)
        movl    %edx, (%rcx)
        ret
    

提交回复
热议问题