Search code examples
cperformancedivisionmicro-optimizationunsigned-integer

Is it possible to get the unsigned quotient and remainer at once in C?


I have seen this question about getting the quotient and remainder in a single operation in C. However the C div and ldiv functions take int and long arguments. But how can I perform unsigned division and save both the remainder and quotient in C? There is to my knowledge no unsigned versions of div or ldiv. Will I have to use inline assembly?


Solution

  • Just use % and / close enough to each other, and let any reasonable modern optimizing compiler translate them to a single instruction.

    Godbolt Example

    struct res { 
        unsigned long long quo;
        unsigned long long rem;
    } 
    f(unsigned long long x, unsigned long long y) {
        struct res r;
        r.quo = x / y;
        r.rem = x % y;
        return r;
    }
    

    Compiled by GCC 11.2 -O2 to:

    f:
            mov     rax, rdi
            xor     edx, edx
            div     rsi
            ret