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