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