xref: /reactos/sdk/lib/crt/math/fabs.c (revision b85afdfd)
1*b85afdfdSTimo Kreuzer /*
2*b85afdfdSTimo Kreuzer  * PROJECT:     ReactOS CRT library
3*b85afdfdSTimo Kreuzer  * LICENSE:     MIT (https://spdx.org/licenses/MIT)
4*b85afdfdSTimo Kreuzer  * PURPOSE:     Portable implementation of fabs
5*b85afdfdSTimo Kreuzer  * COPYRIGHT:   Copyright 2021 Timo Kreuzer <timo.kreuzer@reactos.org>
6*b85afdfdSTimo Kreuzer  */
7*b85afdfdSTimo Kreuzer 
8*b85afdfdSTimo Kreuzer #include <math.h>
9*b85afdfdSTimo Kreuzer 
10*b85afdfdSTimo Kreuzer #ifdef _MSC_VER
11*b85afdfdSTimo Kreuzer #pragma function(fabs)
12*b85afdfdSTimo Kreuzer #endif
13*b85afdfdSTimo Kreuzer 
14*b85afdfdSTimo Kreuzer _Check_return_
15*b85afdfdSTimo Kreuzer double
16*b85afdfdSTimo Kreuzer __cdecl
fabs(_In_ double x)17*b85afdfdSTimo Kreuzer fabs(
18*b85afdfdSTimo Kreuzer     _In_ double x)
19*b85afdfdSTimo Kreuzer {
20*b85afdfdSTimo Kreuzer     /* Load the value as uint64 */
21*b85afdfdSTimo Kreuzer     unsigned long long u64 = *(unsigned long long*)&x;
22*b85afdfdSTimo Kreuzer 
23*b85afdfdSTimo Kreuzer     /* Clear the sign bit */
24*b85afdfdSTimo Kreuzer     u64 &= ~(1ULL << 63);
25*b85afdfdSTimo Kreuzer 
26*b85afdfdSTimo Kreuzer     /* Check for NAN */
27*b85afdfdSTimo Kreuzer     if (u64 > 0x7FF0000000000000ull)
28*b85afdfdSTimo Kreuzer     {
29*b85afdfdSTimo Kreuzer #ifdef _M_IX86
30*b85afdfdSTimo Kreuzer         /* Set error bit */
31*b85afdfdSTimo Kreuzer         *(unsigned long long*)&x |= 0x0008000000000000ull;
32*b85afdfdSTimo Kreuzer #endif
33*b85afdfdSTimo Kreuzer         return x;
34*b85afdfdSTimo Kreuzer     }
35*b85afdfdSTimo Kreuzer 
36*b85afdfdSTimo Kreuzer     /* Convert back to double */
37*b85afdfdSTimo Kreuzer     return *(double*)&u64;
38*b85afdfdSTimo Kreuzer }
39