Upgrade MPFR from 2.4.1 to 2.4.2-p3 on the vendor branch.
[dragonfly.git] / contrib / mpfr / get_ui.c
1 /* mpfr_get_ui -- convert a floating-point number to an unsigned long.
2
3 Copyright 2003, 2004, 2006, 2007, 2008, 2009 Free Software Foundation, Inc.
4 Contributed by the Arenaire and Cacao 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 2.1 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.LIB.  If not, write to
20 the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
21 MA 02110-1301, USA. */
22
23 #include "mpfr-impl.h"
24
25 unsigned long
26 mpfr_get_ui (mpfr_srcptr f, mp_rnd_t rnd)
27 {
28   mp_prec_t prec;
29   unsigned long s;
30   mpfr_t x;
31   mp_size_t n;
32   mp_exp_t exp;
33
34   if (!mpfr_fits_ulong_p (f, rnd))
35     {
36       MPFR_SET_ERANGE ();
37       return MPFR_IS_NEG (f) ? 0 : ULONG_MAX;
38     }
39
40   if (MPFR_IS_ZERO (f))
41     return (unsigned long) 0;
42
43   for (s = ULONG_MAX, prec = 0; s != 0; s >>= 1, prec ++);
44
45   /* first round to prec bits */
46   mpfr_init2 (x, prec);
47   mpfr_rint (x, f, rnd);
48
49   /* warning: if x=0, taking its exponent is illegal */
50   if (MPFR_IS_ZERO(x))
51     s = 0;
52   else
53     {
54       /* now the result is in the most significant limb of x */
55       exp = MPFR_GET_EXP (x); /* since |x| >= 1, exp >= 1 */
56       n = MPFR_LIMB_SIZE(x);
57       s = MPFR_MANT(x)[n - 1] >> (BITS_PER_MP_LIMB - exp);
58     }
59
60   mpfr_clear (x);
61
62   return s;
63 }