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?
Asked
Active
Viewed 155 times
3

user16217248
- 3,119
- 19
- 19
- 37
-
I believe GCC offers an optimization flag which will automatically compile contexts using both `div` and `mod` into a single instruction call. – Rogue Nov 30 '21 at 18:40
-
I don't think you should try to find a way to do optimize the code at this level. If you write the operations in the obvious way like `quotient = a / b; remainder = a % b;` and enable optimization in your compiler, you can assume that the compiler will generate optimal code for your target processor. If you really find out that the optimization of your compiler is not sufficient you might use assembly code. – Bodo Nov 30 '21 at 18:42
1 Answers
3
Just use %
and /
close enough to each other, and let any reasonable modern optimizing compiler translate them to a single instruction.
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

user16217248
- 3,119
- 19
- 19
- 37

Pascal Cuoq
- 79,187
- 7
- 161
- 281
-
4Things may have changed in the past few years, but in my experience this approach has not consistently worked over the past decade. "Unreasonable" compilers are still around, as a quick switch to Clang for ARM7 on Compiler Explorer [shows](https://gcc.godbolt.org/z/9bjTWhMTs). I see a call to `__eabi_uldivmod`, but only the quotient is used and the modulo is then computed by backmultiply. – njuffa Nov 30 '21 at 19:19