假设您已经实现了对 uint128 执行数学运算的函数,您可以将数字分成 3 部分并使用 printf 的内置 64 位打印功能。由于最大的 64 位数字是 20 位长,这意味着所有 19 位的十进制数字都可以这样打印,但是由于最大的 128 位数字是 39 位长,我们不能把它分成两部分,因为我们最终可能会得到一个比最大的 64 位数字大的 20 位数字。
这是一种方法,首先除以 1020 得到不大于 3,402,823,669,209,384,634 的商。然后我们将余数(本身不大于 1020)除以 1010 得到另一个商,余数均小于 1020,即两者都适合 64 位整数。
void print_uint128(uint128 value)
{
// First power of 10 larger than 2^64
static const uint128 tenToThe20 = {7766279631452241920ull, 5ull};
static const uint128 tenToThe10 = {10000000000ull, 0ull};
// Do a 128-bit division; assume we have functions to divide, multiply, and
// subtract 128-bit numbers
uint128 quotient1 = div128(value, tenToThe20);
uint128 remainder1 = sub128(value, mul128(quotient, tenToThe20));
uint128 quotient2 = div128(remainder1, tenToThe10);
uint128 remainder2 = sub128(remainder1, mul128(remainder1, tenToThe10));
// Now print out theresult in 3 parts, being careful not to print
// unnecessary leading 0's
if(quotient1.low != 0)
printf("%llu%010llu%010llu", quotient1.low, quotient2.low, remainder2.low);
else if(quotient2.low != 0)
printf("%llu%010llu", quotient2.low, remainder2.low);
else
printf("%llu", remainder2.low);
}