commit 6c81a88f5626d494378a7f28d472ca1e837b4f31
parent d0ae97304a25eb5d67982d30e2857245741b0f66
Author: Santtu Lakkala <inz@inz.fi>
Date: Fri, 23 Sep 2011 15:19:22 +0000
Unsigned long long and gmplib
Diffstat:
1 file changed, 18 insertions(+), 0 deletions(-)
diff --git a/posts/unsigned-long-long-and-gmplib.md b/posts/unsigned-long-long-and-gmplib.md
@@ -0,0 +1,18 @@
+# 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.