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