如何使用 gcc 打印 __uint128_t 数字? [英] how to print __uint128_t number using gcc?

查看:65
本文介绍了如何使用 gcc 打印 __uint128_t 数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有 PRIu128 的行为类似于 中的 PRIu64:

Is there PRIu128 that behaves similar to PRIu64 from <inttypes.h>:

printf("%" PRIu64 "
", some_uint64_value);

或手动逐位转换:

int print_uint128(uint128_t n) {
  if (n == 0)  return printf("0
");

  char str[40] = {0}; // log10(1 << 128) + ''
  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
", s);
}

是唯一的选择吗?

请注意,uint128_t 是我自己的 __uint128_t 类型定义.

Note that uint128_t is my own typedef for __uint128_t.

推荐答案

不,库中不支持打印这些类型.它们甚至不是 C 标准意义上的扩展整数类型.

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.

您从背面开始打印的想法很好,但您可以使用更大的块.在 P99 的一些测试中,我有一个使用

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

uint64_t const d19 = UINT64_C(10000000000000000000);

作为适合 uint64_t 的 10 的最大幂.

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

  uint64_t low = (uint64_t)x;
  // This is UINT64_MAX, the largest number in 64 bit
  // so the longest string that the lower half can occupy
  char buf[] = { "18446744073709551615" };
  sprintf(buf, "%" PRIX64, low);

得到下半部分再与

  uint64_t high = (x >> 64);

上半部分.

这篇关于如何使用 gcc 打印 __uint128_t 数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆