Skip to content

Instantly share code, notes, and snippets.

@optimizedaway
Last active May 6, 2020 10:24
Show Gist options
  • Save optimizedaway/a87c2146db46a10ebb75c580ea84d0f5 to your computer and use it in GitHub Desktop.
Save optimizedaway/a87c2146db46a10ebb75c580ea84d0f5 to your computer and use it in GitHub Desktop.
128 by 64 bit integer division for gcc and clang
#include <stdint.h>
// 128 by 64 bit integer division for gcc and clang
inline uint64_t udiv128_64(unsigned __int128 a, uint64_t b)
{
// We don't want 128 bit software division
uint64_t alo = (uint64_t)a;
uint64_t ahi = (a >> 64);
uint64_t d, e;
__asm__("divq %[b]"
: "=a"(d), "=d"(e)
: [b] "r"(b), "a"(alo), "d"(ahi)
);
return d;
}
inline int64_t idiv128_64(__int128 a, int64_t b)
{
// We don't want 128 bit software division
uint64_t alo = (uint64_t)a;
uint64_t ahi = ((unsigned __int128)a >> 64);
int64_t d, e;
__asm__("idivq %[b]"
: "=a"(d), "=d"(e)
: [b] "r"(b), "a"(alo), "d"(ahi)
);
return d;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment