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

Viewed 85

I am aware of 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?

1 Answers

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

Example: https://gcc.godbolt.org/z/TxeesqTqf

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
Related