C:以10为底打印BigInteger [英] C: print a BigInteger in base 10

查看:85
本文介绍了C:以10为底打印BigInteger的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用此结构表示128位整数:

I am using this struct to represent 128bit integers:

typedef struct {
    uint64_t low, high;
} uint128;

(除非您可以将我指向一个快速的128位整数库,否则无法更改)

(Unless you can point me to a fast 128bit integer library I can not change that)

现在,我想使用printf以10为基数打印这样的值.我可能需要除以10才能做到这一点,但尚未实现除法.

Now I want to print such a value in base 10, using printf. I probably need division by 10 to do that, but no division is implemented yet.

我该怎么做?只要可行,该解决方案就不必超级高效.

How can I do this? The solution does not have to be super efficient, as long as it works.

我喜欢您想出的所有解决方案.你真棒.

I like all solutions you came up with. You are awesome.

推荐答案

void printu128(uint128 n) {
  int d[39] = {0}, i, j;
  for (i = 63; i > -1; i--) {
    if ((n.high >> i) & 1) d[0]++;
    for (j = 0; j < 39; j++) d[j] *= 2;
    for (j = 0; j < 38; j++) d[j+1] += d[j]/10, d[j] %= 10;
  }
  for (i = 63; i > -1; i--) {
    if ((n.low >> i) & 1) d[0]++;
    if (i > 0) for (j = 0; j < 39; j++) d[j] *= 2;
    for (j = 0; j < 38; j++) d[j+1] += d[j]/10, d[j] %= 10;
  }
  for (i = 38; i > 0; i--) if (d[i] > 0) break;
  for (; i > -1; i--) putchar('0'+d[i]);
}

这篇关于C:以10为底打印BigInteger的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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