Skip to content

Instantly share code, notes, and snippets.

@danlark1
Last active July 18, 2020 07:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danlark1/b89d67ad5e1989c0336c3ec921e5c67a to your computer and use it in GitHub Desktop.
Save danlark1/b89d67ad5e1989c0336c3ec921e5c67a to your computer and use it in GitHub Desktop.
// dividend / divisor, remainder is stored in rem.
uint128 __udivmodti4(uint128 dividend, uint128 divisor, uint128* rem) {
if (divisor > dividend) {
if (rem)
*rem = dividend;
return 0;
}
// 64 bit divisor implementation
...
// end
// Calculate the distance between most significant bits, 128 > shift >= 0.
int shift = Distance(dividend, divisor);
divisor <<= shift;
quotient.low = 0;
quotient.high = 0;
for (; shift >= 0; --shift) {
quotient.low <<= 1;
const int128 s = (int128)(divisor.all - dividend.all - 1) >> 127;
quotient.low |= s & 1;
dividend.all -= divisor.all & s;
divisor >>= 1;
}
if (rem)
*rem = dividend;
return quotient;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment