Unsigned long long and gmplib

September 23, 2011 on 6:19 pm | In geeky | No Comments

While doing some projecteuler's, I wanted to convert an unsigned long long (64-bit unsigned integer on an 32-bit machine) to mpz_t (and possible vice versa). The API does not have a convenient method for this, but it is possible using the mpz_import and mpz_export; it goes something like this:

mpz_t mp;
unsigned long long ull = 42;


/* mp = ull */
mpz_import(mp, 1, 1, sizeof(ull), 0, 0, &ull);

/* ull = mp; note: this needs bondary checking */
if (mpz_sizeinbase(mp, 256) <= sizeof(ull))
        mpz_export(&ull, NULL, 1, sizeof(ull), 0, 0, mp);

For signed integers you'll need some additional tricks, as mpz_import and mpz_export do not support negatives; just negate before and after conversion (hint: mpz_neg()). The boundary checking in export case is slightly more problematic then, and is likely easier to do after export.

No Comments yet »

RSS feed for comments on this post. TrackBack URI

Leave a comment

XHTML: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Powered by WordPress.
Entries and comments feeds. Valid XHTML and CSS. ^Top^