inz.fi

Unnamed repository; edit this file 'description' to name the repository.
Log | Files | Refs

unsigned-long-long-and-gmplib.md (918B)


      1 # Unsigned long long and gmplib
      2 
      3  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:
      4 
      5 	mpz_t mp;
      6 	unsigned long long ull = 42;
      7 	
      8 	mpz_init(mp);
      9 	
     10 	/* mp = ull */
     11 	mpz_import(mp, 1, 1, sizeof(ull), 0, 0, &ull);
     12 	
     13 	/* ull = mp; note: this needs bondary checking */
     14 	if (mpz_sizeinbase(mp, 256) <= sizeof(ull))
     15 	        mpz_export(&ull, NULL, 1, sizeof(ull), 0, 0, mp);
     16 	mpz_clear(mp);
     17 
     18  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.