1/* mpf_get_si -- mpf to long conversion 2 3Copyright 2001, 2002, 2004 Free Software Foundation, Inc. 4 5This file is part of the GNU MP Library. 6 7The GNU MP Library is free software; you can redistribute it and/or modify 8it under the terms of either: 9 10 * the GNU Lesser General Public License as published by the Free 11 Software Foundation; either version 3 of the License, or (at your 12 option) any later version. 13 14or 15 16 * the GNU General Public License as published by the Free Software 17 Foundation; either version 2 of the License, or (at your option) any 18 later version. 19 20or both in parallel, as here. 21 22The GNU MP Library is distributed in the hope that it will be useful, but 23WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 24or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 25for more details. 26 27You should have received copies of the GNU General Public License and the 28GNU Lesser General Public License along with the GNU MP Library. If not, 29see https://www.gnu.org/licenses/. */ 30 31#include "gmp-impl.h" 32 33 34/* Any fraction bits are truncated, meaning simply discarded. 35 36 For values bigger than a long, the low bits are returned, like 37 mpz_get_si, but this isn't documented. 38 39 Notice this is equivalent to mpz_set_f + mpz_get_si. 40 41 42 Implementation: 43 44 fl is established in basically the same way as for mpf_get_ui, see that 45 code for explanations of the conditions. 46 47 However unlike mpf_get_ui we need an explicit return 0 for exp<=0. When 48 f is a negative fraction (ie. size<0 and exp<=0) we can't let fl==0 go 49 through to the zany final "~ ((fl - 1) & LONG_MAX)", that would give 50 -0x80000000 instead of the desired 0. */ 51 52long 53mpf_get_si (mpf_srcptr f) __GMP_NOTHROW 54{ 55 mp_exp_t exp; 56 mp_size_t size, abs_size; 57 mp_srcptr fp; 58 mp_limb_t fl; 59 60 exp = EXP (f); 61 size = SIZ (f); 62 fp = PTR (f); 63 64 /* fraction alone truncates to zero 65 this also covers zero, since we have exp==0 for zero */ 66 if (exp <= 0) 67 return 0L; 68 69 /* there are some limbs above the radix point */ 70 71 fl = 0; 72 abs_size = ABS (size); 73 if (abs_size >= exp) 74 fl = fp[abs_size-exp]; 75 76#if BITS_PER_ULONG > GMP_NUMB_BITS 77 if (exp > 1 && abs_size+1 >= exp) 78 fl |= fp[abs_size - exp + 1] << GMP_NUMB_BITS; 79#endif 80 81 if (size > 0) 82 return fl & LONG_MAX; 83 else 84 /* this form necessary to correctly handle -0x80..00 */ 85 return -1 - (long) ((fl - 1) & LONG_MAX); 86} 87