Converting to Base 256

Ken Smith kgsmith at gmail.com
Tue Dec 12 21:28:22 CET 2006


I have data files which are in hexidecimal ASCII representation with
one number per line.  Eg.

line 1: 1a2b3c90effe487db13f45c9872b309e47234a
line 2: 7e456b4f75aba74e56fa456c7a4567e2bf2345ecefbe
etc.

I need to convert these into byte strings such that

line1[0] = 0x1a
line1[1] = 0x2b
line1[2] = 0x3c
etc.

My first instinct was to crawl through the string and perform a hand
calculation storing the result of every two nibbles into a byte in the
final array.  Then I remembered that GnuMP can handle such large
numbers naturally.  My first attempt to use GnuMP for this task
resulted in the following.  (Incidentally, this is my first attempt to
use GnuMP for any task.)

1: const char* line = "1a2b3c90effe487db13f45c9872b309e47234a";
2: mpz_t line_as_num;
3:
4: mpz_init_set_str(line_as_num, line, 16);
5:
6: /* so far so good */
7:
8: char* line_as_bytes = mpz_get_str(NULL, 256, line_as_num); /* uh oh */

Clearly, line 8 of this source snippet is invalid as mpz_get_str maxes
out at base 36.  A quick test shows that line_as_bytes is NULL after
line 8 as I would expect.  It makes sense for mpz_get_str to max out
at base 36 since the function constrains itself to generating null
terminated strings containing only alphanumeric characters.

Is there any way GnuMP can make what I'm trying to do as easy as I
thought it might be?

  Ken Smith

ps.  I'm not a list member so please include this address in any
followup responses.  Thank you.


More information about the gmp-discuss mailing list