Unsigned long long and gmplib

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;

mpz_init(mp);

/* 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);
mpz_clear(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.