1 /* 2 * ==================================================== 3 * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. 4 * 5 * Developed at SunPro, a Sun Microsystems, Inc. business. 6 * Permission to use, copy, modify, and distribute this 7 * software is freely granted, provided that this notice 8 * is preserved. 9 * ==================================================== 10 * 11 * From: @(#)s_floor.c 5.1 93/09/24 12 */ 13 14 /* 15 * truncl(x) 16 * Return x rounded toward 0 to integral value 17 * Method: 18 * Bit twiddling. 19 * Exception: 20 * Inexact flag raised if x not equal to truncl(x). 21 */ 22 23 #include <float.h> 24 #include <math.h> 25 #include <stdint.h> 26 27 #include "fpmath.h" 28 29 #ifdef LDBL_IMPLICIT_NBIT 30 #define MANH_SIZE (LDBL_MANH_SIZE + 1) 31 #else 32 #define MANH_SIZE LDBL_MANH_SIZE 33 #endif 34 35 static const long double huge = 1.0e300; 36 static const float zero[] = { 0.0, -0.0 }; 37 38 long double truncl(long double x)39truncl(long double x) 40 { 41 union IEEEl2bits u = { .e = x }; 42 int e = u.bits.exp - LDBL_MAX_EXP + 1; 43 44 if (e < MANH_SIZE - 1) { 45 if (e < 0) { /* raise inexact if x != 0 */ 46 if (huge + x > 0.0) 47 u.e = zero[u.bits.sign]; 48 } else { 49 uint64_t m = ((1llu << MANH_SIZE) - 1) >> (e + 1); 50 if (((u.bits.manh & m) | u.bits.manl) == 0) 51 return (x); /* x is integral */ 52 if (huge + x > 0.0) { /* raise inexact flag */ 53 u.bits.manh &= ~m; 54 u.bits.manl = 0; 55 } 56 } 57 } else if (e < LDBL_MANT_DIG - 1) { 58 uint64_t m = (uint64_t)-1 >> (64 - LDBL_MANT_DIG + e + 1); 59 if ((u.bits.manl & m) == 0) 60 return (x); /* x is integral */ 61 if (huge + x > 0.0) /* raise inexact flag */ 62 u.bits.manl &= ~m; 63 } 64 return (u.e); 65 } 66