Is there PRIu128
that behaves similar to PRIu64
from <inttypes.h>
:
printf("%" PRIu64 "\n", some_uint64_value);
Or converting manually digit by digit:
int print_uint128(uint128_t n) {
if (n == 0) return printf("0\n");
char str[40] = {0}; // log10(1 << 128) + '\0'
char *s = str + sizeof(str) - 1; // start at the end
while (n != 0) {
if (s == str) return -1; // never happens
*--s = "0123456789"[n % 10]; // save last digit
n /= 10; // drop it
}
return printf("%s\n", s);
}
is the only option?
Note that uint128_t
is my own typedef for __uint128_t
.
Working off of abelenky's answer above, I came up with this.
Which seems to work as intended.
You can use this simple macro :
No. Instead to print in decimal, print to a string.
The size of string buffer needed is just enough to do the job per the value of
x
.Test. Worst case buffer size: 41.
Output
No there isn't support in the library for printing these types. They aren't even extended integer types in the sense of the C standard.
Your idea for starting the printing from the back is a good one, but you could use much larger chunks. In some tests for P99 I have such a function that uses
as the largest power of 10 that fits into an
uint64_t
.As decimal, these big numbers get unreadable very soon so another, easier, option is to print them in hex. Then you can do something like
to get the lower half and then basically the same with
for the upper half.
I don't have a built-in solution, but division/modulus is expensive. You can convert binary to decimal with just shifts.
(But apparently 128-bit division/modulus are not as expensive as I thought. On a Phenom 9600 with GCC 4.7 and Clang 3.1 at
-O2
, this seems to run a 2x-3x slower than OP's method.)much like #3