2 * Copyright (c) 2011 Jiri Zarevucky
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
9 * - Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * - Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 * - The name of the author may not be used to endorse or promote products
15 * derived from this software without specific prior written permission.
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 /** @addtogroup libposix
32 /** @file Backend for floating point conversions.
35 #define LIBPOSIX_INTERNAL
38 #include "../stdbool.h"
40 #include "../internal/common.h"
41 #include "../stdlib.h"
43 #include "../assert.h"
45 #include "../stdint.h"
46 #include "../strings.h"
48 #include "../limits.h"
53 #define HUGE_VALL (+1.0l / +0.0l)
57 #define abs(x) (((x) < 0) ? -(x) : (x))
60 /* If the constants are not defined, use double precision as default. */
62 #define LDBL_MANT_DIG 53
65 #define LDBL_MAX_EXP 1024
68 #define LDBL_MIN_EXP (-1021)
74 #define LDBL_MIN 2.2250738585072014E-308
77 /* power functions ************************************************************/
79 #if LDBL_MAX_EXP >= 16384
80 const int MAX_POW5
= 12;
82 const int MAX_POW5
= 8;
85 /* The value at index i is approximately 5**(2**i). */
86 long double pow5
[] = {
92 0x4EE2D6D415B85ACEF81p
0l,
93 0x184F03E93FF9F4DAA797ED6E38ED6p
36l,
94 0x127748F9301D319BF8CDE66D86D62p
185l,
95 0x154FDD7F73BF3BD1BBB77203731FDp
482l,
96 #if LDBL_MAX_EXP >= 16384
97 0x1C633415D4C1D238D98CAB8A978A0p
1076l,
98 0x192ECEB0D02EA182ECA1A7A51E316p
2265l,
99 0x13D1676BB8A7ABBC94E9A519C6535p
4643l,
100 0x188C0A40514412F3592982A7F0094p
9398l,
104 #if LDBL_MAX_EXP >= 16384
105 const int MAX_POW2
= 15;
107 const int MAX_POW2
= 9;
111 long double pow2
[] = {
122 #if LDBL_MAX_EXP >= 16384
131 * Multiplies a number by a power of five.
132 * The result may be inexact and may not be the best possible approximation.
134 * @param mant Number to be multiplied.
135 * @param exp Base 5 exponent.
136 * @return mant multiplied by 5**exp
138 static long double mul_pow5(long double mant
, int exp
)
140 if (mant
== 0.0l || mant
== HUGE_VALL
) {
144 if (abs(exp
) >> (MAX_POW5
+ 1) != 0) {
145 /* Too large exponent. */
147 return exp
< 0 ? LDBL_MIN
: HUGE_VALL
;
152 for (int bit
= 0; bit
<= MAX_POW5
; ++bit
) {
153 /* Multiply by powers of five bit-by-bit. */
154 if (((exp
>> bit
) & 1) != 0) {
165 for (int bit
= 0; bit
<= MAX_POW5
; ++bit
) {
166 /* Multiply by powers of five bit-by-bit. */
167 if (((exp
>> bit
) & 1) != 0) {
169 if (mant
== HUGE_VALL
) {
182 * Multiplies a number by a power of two. This is always exact.
184 * @param mant Number to be multiplied.
185 * @param exp Base 2 exponent.
186 * @return mant multiplied by 2**exp.
188 static long double mul_pow2(long double mant
, int exp
)
190 if (mant
== 0.0l || mant
== HUGE_VALL
) {
194 if (exp
> LDBL_MAX_EXP
|| exp
< LDBL_MIN_EXP
) {
196 return exp
< 0 ? LDBL_MIN
: HUGE_VALL
;
201 for (int i
= 0; i
<= MAX_POW2
; ++i
) {
202 if (((exp
>> i
) & 1) != 0) {
212 for (int i
= 0; i
<= MAX_POW2
; ++i
) {
213 if (((exp
>> i
) & 1) != 0) {
215 if (mant
== HUGE_VALL
) {
226 /* end power functions ********************************************************/
231 * Convert decimal string representation of the floating point number.
232 * Function expects the string pointer to be already pointed at the first
233 * digit (i.e. leading optional sign was already consumed by the caller).
235 * @param sptr Pointer to the storage of the string pointer. Upon successful
236 * conversion, the string pointer is updated to point to the first
237 * unrecognized character.
238 * @return An approximate representation of the input floating-point number.
240 static long double parse_decimal(const char **sptr
)
242 assert(sptr
!= NULL
);
243 assert (*sptr
!= NULL
);
245 const int DEC_BASE
= 10;
246 const char DECIMAL_POINT
= '.';
247 const char EXPONENT_MARK
= 'e';
249 const char *str
= *sptr
;
250 long double significand
= 0;
253 /* number of digits parsed so far */
254 int parsed_digits
= 0;
255 bool after_decimal
= false;
257 while (isdigit(*str
) || (!after_decimal
&& *str
== DECIMAL_POINT
)) {
258 if (*str
== DECIMAL_POINT
) {
259 after_decimal
= true;
264 if (parsed_digits
== 0 && *str
== '0') {
265 /* Nothing, just skip leading zeros. */
266 } else if (parsed_digits
< LDBL_DIG
) {
267 significand
= significand
* DEC_BASE
+ (*str
- '0');
274 /* Decrement exponent if we are parsing the fractional part. */
282 if (tolower(*str
) == EXPONENT_MARK
) {
285 /* Returns MIN/MAX value on error, which is ok. */
286 long exp
= strtol(str
, (char **) &str
, DEC_BASE
);
288 if (exponent
> 0 && exp
> LONG_MAX
- exponent
) {
290 } else if (exponent
< 0 && exp
< LONG_MIN
- exponent
) {
299 /* Return multiplied by a power of ten. */
300 return mul_pow2(mul_pow5(significand
, exponent
), exponent
);
304 * Derive a hexadecimal digit from its character representation.
306 * @param ch Character representation of the hexadecimal digit.
307 * @return Digit value represented by an integer.
309 static inline int hex_value(char ch
)
314 return 10 + tolower(ch
) - 'a';
319 * Convert hexadecimal string representation of the floating point number.
320 * Function expects the string pointer to be already pointed at the first
321 * digit (i.e. leading optional sign and 0x prefix were already consumed
324 * @param sptr Pointer to the storage of the string pointer. Upon successful
325 * conversion, the string pointer is updated to point to the first
326 * unrecognized character.
327 * @return Representation of the input floating-point number.
329 static long double parse_hexadecimal(const char **sptr
)
331 assert(sptr
!= NULL
&& *sptr
!= NULL
);
333 const int DEC_BASE
= 10;
334 const int HEX_BASE
= 16;
335 const char DECIMAL_POINT
= '.';
336 const char EXPONENT_MARK
= 'p';
338 const char *str
= *sptr
;
339 long double significand
= 0;
342 /* number of bits parsed so far */
344 bool after_decimal
= false;
346 while (posix_isxdigit(*str
) || (!after_decimal
&& *str
== DECIMAL_POINT
)) {
347 if (*str
== DECIMAL_POINT
) {
348 after_decimal
= true;
353 if (parsed_bits
== 0 && *str
== '0') {
354 /* Nothing, just skip leading zeros. */
355 } else if (parsed_bits
<= LDBL_MANT_DIG
) {
356 significand
= significand
* HEX_BASE
+ hex_value(*str
);
370 if (tolower(*str
) == EXPONENT_MARK
) {
373 /* Returns MIN/MAX value on error, which is ok. */
374 long exp
= strtol(str
, (char **) &str
, DEC_BASE
);
376 if (exponent
> 0 && exp
> LONG_MAX
- exponent
) {
378 } else if (exponent
< 0 && exp
< LONG_MIN
- exponent
) {
387 /* Return multiplied by a power of two. */
388 return mul_pow2(significand
, exponent
);
392 * Converts a string representation of a floating-point number to
393 * its native representation. Largely POSIX compliant, except for
394 * locale differences (always uses '.' at the moment) and rounding.
395 * Decimal strings are NOT guaranteed to be correctly rounded. This function
396 * should return a good enough approximation for most purposes but if you
397 * depend on a precise conversion, use hexadecimal representation.
398 * Hexadecimal strings are currently always rounded towards zero, regardless
399 * of the current rounding mode.
401 * @param nptr Input string.
402 * @param endptr If non-NULL, *endptr is set to the position of the first
403 * unrecognized character.
404 * @return An approximate representation of the input floating-point number.
406 long double posix_strtold(const char *restrict nptr
, char **restrict endptr
)
408 assert(nptr
!= NULL
);
410 const int RADIX
= '.';
413 bool negative
= false;
414 /* current position in the string */
417 /* skip whitespace */
418 while (isspace(nptr
[i
])) {
432 if (posix_strncasecmp(&nptr
[i
], "nan", 3) == 0) {
434 // TODO: handle the parenthesised case
436 if (endptr
!= NULL
) {
437 *endptr
= (char *) nptr
;
443 /* check for Infinity */
444 if (posix_strncasecmp(&nptr
[i
], "inf", 3) == 0) {
446 if (posix_strncasecmp(&nptr
[i
], "inity", 5) == 0) {
450 if (endptr
!= NULL
) {
451 *endptr
= (char *) &nptr
[i
];
453 return negative
? -HUGE_VALL
: +HUGE_VALL
;
456 /* check for a hex number */
457 if (nptr
[i
] == '0' && tolower(nptr
[i
+ 1]) == 'x' &&
458 (posix_isxdigit(nptr
[i
+ 2]) ||
459 (nptr
[i
+ 2] == RADIX
&& posix_isxdigit(nptr
[i
+ 3])))) {
462 const char *ptr
= &nptr
[i
];
463 /* this call sets errno if appropriate. */
464 long double result
= parse_hexadecimal(&ptr
);
465 if (endptr
!= NULL
) {
466 *endptr
= (char *) ptr
;
468 return negative
? -result
: result
;
471 /* check for a decimal number */
472 if (isdigit(nptr
[i
]) || (nptr
[i
] == RADIX
&& isdigit(nptr
[i
+ 1]))) {
473 const char *ptr
= &nptr
[i
];
474 /* this call sets errno if appropriate. */
475 long double result
= parse_decimal(&ptr
);
476 if (endptr
!= NULL
) {
477 *endptr
= (char *) ptr
;
479 return negative
? -result
: result
;
482 /* nothing to parse */
483 if (endptr
!= NULL
) {
484 *endptr
= (char *) nptr
;