]> git.ipfire.org Git - thirdparty/glibc.git/blob - sysdeps/ieee754/flt-32/s_fromfpf_main.c
Update copyright dates with scripts/update-copyrights.
[thirdparty/glibc.git] / sysdeps / ieee754 / flt-32 / s_fromfpf_main.c
1 /* Round to integer type. flt-32 version.
2 Copyright (C) 2016-2017 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
4
5 The GNU C Library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 The GNU C Library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with the GNU C Library; if not, see
17 <http://www.gnu.org/licenses/>. */
18
19 #include <errno.h>
20 #include <fenv.h>
21 #include <math.h>
22 #include <math_private.h>
23 #include <stdbool.h>
24 #include <stdint.h>
25
26 #define BIAS 0x7f
27 #define MANT_DIG 24
28
29 #if UNSIGNED
30 # define RET_TYPE uintmax_t
31 #else
32 # define RET_TYPE intmax_t
33 #endif
34
35 #include <fromfp.h>
36
37 RET_TYPE
38 FUNC (float x, int round, unsigned int width)
39 {
40 if (width > INTMAX_WIDTH)
41 width = INTMAX_WIDTH;
42 uint32_t ix;
43 GET_FLOAT_WORD (ix, x);
44 bool negative = (ix & 0x80000000) != 0;
45 if (width == 0)
46 return fromfp_domain_error (negative, width);
47 ix &= 0x7fffffff;
48 if (ix == 0)
49 return 0;
50 int exponent = ix >> (MANT_DIG - 1);
51 exponent -= BIAS;
52 int max_exponent = fromfp_max_exponent (negative, width);
53 if (exponent > max_exponent)
54 return fromfp_domain_error (negative, width);
55
56 ix &= ((1U << (MANT_DIG - 1)) - 1);
57 ix |= 1U << (MANT_DIG - 1);
58 uintmax_t uret;
59 bool half_bit, more_bits;
60 if (exponent >= MANT_DIG - 1)
61 {
62 uret = ix;
63 uret <<= exponent - (MANT_DIG - 1);
64 half_bit = false;
65 more_bits = false;
66 }
67 else if (exponent >= -1)
68 {
69 uint32_t h = 1U << (MANT_DIG - 2 - exponent);
70 half_bit = (ix & h) != 0;
71 more_bits = (ix & (h - 1)) != 0;
72 uret = ix >> (MANT_DIG - 1 - exponent);
73 }
74 else
75 {
76 uret = 0;
77 half_bit = false;
78 more_bits = true;
79 }
80 return fromfp_round_and_return (negative, uret, half_bit, more_bits, round,
81 exponent, max_exponent, width);
82 }