10

I have in C++ a vector of 32 bits integers (variable size, continous memory; like a C-array), representing a number in base 4294967296. I would like to print it in base 10.

These numbers can be extremely big and take over a few megabytes of memory.

What would be the best way to do this in terms of performance? Can I use GMP to do this?

  • just pure curiosity.. 2^32000000 with integer precision? what do are you doing? – Karoly Horvath Oct 22 '11 at 23:24
  • @yi_H 2^32 to be exact. Basically I want to print a base 2^32 integer in a human-readable form. Humans don't know 2^32 characters, so I only want to use the digits 0..9. –  Oct 22 '11 at 23:27
  • yes, you repeated your question. you said it's base 2^32 and it takes a couple of megabytes, **so** the numbers are in the order of 2^32000000. with integer *precision*. my question was: what the heck are you doing? – Karoly Horvath Oct 22 '11 at 23:30
  • +1 just for doing something I consider unusual =] – James Webster Oct 22 '11 at 23:31
  • @yi_H sorry, I misunderstood your comment. My program is an interpreter for a programming language. It has specific goals, including support for giant numbers. –  Oct 22 '11 at 23:34
  • But humans know base 16(hexadecimal). And conversion from base 2^32 to base 16 is trivial and unlike base 10 it preserves most of the properties of the original representation. – CodesInChaos Oct 22 '11 at 23:34
  • 2
    @WTP: you should use GMP for data representation too, not only for printing... – Karoly Horvath Oct 22 '11 at 23:36
  • What exactly *is* base 2^32? Never heard of it and Google doesn't give any clue. – Xeo Oct 23 '11 at 00:15
  • 1
    @Xeo in base 2^32 you have 2^32 different digits, like in base 10 you have 10 different digits (0 to 9), and in base 2 you have 2 different digits (1 and 0). –  Oct 23 '11 at 00:41

1 Answers1

7

Yes, you can use GMP for this. The function that you're looking for is mpn_get_str:

http://gmplib.org/manual/Low_002dlevel-Functions.html#Low_002dlevel-Functions

Now the only issue is the size of mp_limb_t. It is either a 32-bit integer or a 64-bit integer depending on the platform.

  • If it's a 32-bit integer, then you can call the function directly on your array of 32-bit integers. (if the endian matches)
  • If it's a 64-bit integer, you may be able to still use it with just a pointer cast. (depending on the alignment and the endianness) Otherwise, you'll have to copy your array into an array of 64-bit integers before you can call mpn_get_str.

Alternatively, it might be easier to use the mpz integer class. Import your integer array into a large integer, then print it back out in base 10.

Mysticial
  • 464,885
  • 45
  • 335
  • 332