1/* mpfr_get_uj -- convert a MPFR number to a huge machine unsigned integer 2 3Copyright 2004, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013 Free Software Foundation, Inc. 4Contributed by the AriC and Caramel projects, INRIA. 5 6This file is part of the GNU MPFR Library. 7 8The GNU MPFR Library is free software; you can redistribute it and/or modify 9it under the terms of the GNU Lesser General Public License as published by 10the Free Software Foundation; either version 3 of the License, or (at your 11option) any later version. 12 13The GNU MPFR Library is distributed in the hope that it will be useful, but 14WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 15or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public 16License for more details. 17 18You should have received a copy of the GNU Lesser General Public License 19along with the GNU MPFR Library; see the file COPYING.LESSER. If not, see 20http://www.gnu.org/licenses/ or write to the Free Software Foundation, Inc., 2151 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. */ 22 23#ifdef HAVE_CONFIG_H 24# include "config.h" /* for a build within gmp */ 25#endif 26 27#include "mpfr-intmax.h" 28#include "mpfr-impl.h" 29 30#ifdef _MPFR_H_HAVE_INTMAX_T 31 32uintmax_t 33mpfr_get_uj (mpfr_srcptr f, mpfr_rnd_t rnd) 34{ 35 uintmax_t r; 36 mpfr_prec_t prec; 37 mpfr_t x; 38 39 if (MPFR_UNLIKELY (!mpfr_fits_uintmax_p (f, rnd))) 40 { 41 MPFR_SET_ERANGE (); 42 return MPFR_IS_NAN (f) || MPFR_IS_NEG (f) ? 43 (uintmax_t) 0 : MPFR_UINTMAX_MAX; 44 } 45 46 if (MPFR_IS_ZERO (f)) 47 return (uintmax_t) 0; 48 49 /* determine the precision of uintmax_t */ 50 for (r = MPFR_UINTMAX_MAX, prec = 0; r != 0; r /= 2, prec++) 51 { } 52 53 /* Now, r = 0. */ 54 55 mpfr_init2 (x, prec); 56 mpfr_rint (x, f, rnd); 57 MPFR_ASSERTN (MPFR_IS_FP (x)); 58 59 if (MPFR_NOTZERO (x)) 60 { 61 mp_limb_t *xp; 62 int sh, n; /* An int should be sufficient in this context. */ 63 64 MPFR_ASSERTN (MPFR_IS_POS (x)); 65 xp = MPFR_MANT (x); 66 sh = MPFR_GET_EXP (x); 67 MPFR_ASSERTN ((mpfr_prec_t) sh <= prec); 68 for (n = MPFR_LIMB_SIZE(x) - 1; n >= 0; n--) 69 { 70 sh -= GMP_NUMB_BITS; 71 r += (sh >= 0 72 ? (uintmax_t) xp[n] << sh 73 : (uintmax_t) xp[n] >> (- sh)); 74 } 75 } 76 77 mpfr_clear (x); 78 79 return r; 80} 81 82#endif 83