在C打印大型基地256数组基地10 [英] Print large base 256 array in base 10 in c

查看:269
本文介绍了在C打印大型基地256数组基地10的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C无符号的字符我想在基地10打印的数组,我卡住了。我认为这将在code得到更好的解释,因此,考虑到:

I have an array of unsigned chars in c I am trying to print in base 10, and I am stuck. I think this will be better explained in code, so, given:

unsigned char n[3];
char[0] = 1;
char[1] = 2;
char[2] = 3;

我要打印197121。

I would like to print 197121.

这是微不足道的小基地256阵列。可以简单地1 * 256 ^ 0 + 2 * 256 ^ 1 + 3 * 256 ^ 2。

This is trivial with small base 256 arrays. One can simply 1 * 256 ^ 0 + 2 * 256 ^ 1 + 3 * 256 ^ 2.

然而,如果我的阵列是100字节大,那么这很快成为一个问题。在C中没有整数类型为100字节大,这就是为什么我在存储无符号的字符数组号开始。

However, if my array was 100 bytes large, then this quickly becomes a problem. There is no integral type in C that is 100 bytes large, which is why I'm storing numbers in unsigned char arrays to begin with.

我怎么在基地10高效打印这个数字呢?

How am I supposed to efficiently print this number out in base 10?

我是有点失落。

推荐答案

有没有简单的方法只使用标准C库做。你要么必须自己编写(不推荐)的功能,或使用外部库,如 GMP

There's no easy way to do it using only the standard C library. You'll either have to write the function yourself (not recommended), or use an external library such as GMP.

例如,使用GMP,你可以这样做:

For example, using GMP, you could do:

unsigned char n[100];  // number to print

mpz_t num;
mpz_import(num, 100, -1, 1, 0, 0, n);  // convert byte array into GMP format
mpz_out_str(stdout, 10, num);  // print num to stdout in base 10
mpz_clear(num);  // free memory for num

这篇关于在C打印大型基地256数组基地10的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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