Last active
April 26, 2025 15:03
-
-
Save optimizedaway/a87c2146db46a10ebb75c580ea84d0f5 to your computer and use it in GitHub Desktop.
128 by 64 bit integer division for gcc and clang
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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