Convert really big number from binary to decimal and print it

AlannY picture AlannY · Jun 6, 2009 · Viewed 8.3k times · Source

I know how to convert binary to decimal. I know at least 2 methods: table and power ;-)

I want to convert binary to decimal and print this decimal. Moreover, I'm not interested in this `decimal'; I want just to print it.

But, as I wrote above, I know only 2 methods to convert binary to decimal and both of them required addition. So, I'm computing some value for 1 or 0 in binary and add it to the remembered value. This is a thin place. I have a really-really big number (1 and 64 zeros). While converting I need to place some intermediate result in some 'variable'. In C, I have an `int' type, which is 4 bytes only and not more than 10^11.

So, I don't have enough memory to store intermedite result while converting from binary to decimal. As I wrote above, I'm not interested in THAT decimal, I just want to print the result. But, I don't see any other ways to solve it ;-( Is there any solution to "just print" from binary?

Or, maybe, I should use something like BCD (Binary Coded Decimal) for intermediate representation? I really don't want to use this, 'cause it is not so cross-platform (Intel's processors have a built-in feature, but for other I'll need to write own implementation).

I would glad to hear your thoughts. Thanks for patience.

Language: C.

Answer

Adam Rosenfield picture Adam Rosenfield · Jun 6, 2009

I highly recommend using a library such as GMP (GNU multiprecision library). You can use the mpz_t data type for large integers, the various import/export routines to get your data into an mpz_t, and then use mpz_out_str() to print it out in base 10.