s_truncl.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. * truncl(x)
  15. * Return x rounded toward 0 to integral value
  16. * Method:
  17. * Bit twiddling.
  18. * Exception:
  19. * Inexact flag raised if x not equal to truncl(x).
  20. */
  21. #include <sys/types.h>
  22. #include <machine/ieee.h>
  23. #include <float.h>
  24. #include <openlibm_math.h>
  25. #include <stdint.h>
  26. #include "math_private.h"
  27. #ifdef LDBL_IMPLICIT_NBIT
  28. #define MANH_SIZE (EXT_FRACHBITS + EXT_FRACHMBITS + 1)
  29. #else
  30. #define MANH_SIZE (EXT_FRACHBITS + EXT_FRACHMBITS)
  31. #endif
  32. static const long double huge = 1.0e300;
  33. static const float zero[] = { 0.0, -0.0 };
  34. long double
  35. truncl(long double x)
  36. {
  37. int e;
  38. int64_t ix0, ix1;
  39. GET_LDOUBLE_WORDS64(ix0,ix1,x);
  40. e = ((ix0>>48)&0x7fff) - LDBL_MAX_EXP + 1;
  41. if (e < MANH_SIZE - 1) {
  42. if (e < 0) { /* raise inexact if x != 0 */
  43. if (huge + x > 0.0)
  44. return (zero[((ix0>>48)&0x8000)!=0]);
  45. } else {
  46. uint64_t m = ((1llu << MANH_SIZE) - 1) >> (e + 1);
  47. if (((ix0 & m) | ix1) == 0)
  48. return (x); /* x is integral */
  49. if (huge + x > 0.0) { /* raise inexact flag */
  50. ix0 &= ~m;
  51. ix1 = 0;
  52. }
  53. }
  54. } else if (e < LDBL_MANT_DIG - 1) {
  55. uint64_t m = (uint64_t)-1 >> (64 - LDBL_MANT_DIG + e + 1);
  56. if ((ix1 & m) == 0)
  57. return (x); /* x is integral */
  58. if (huge + x > 0.0) /* raise inexact flag */
  59. ix1 &= ~m;
  60. }
  61. SET_LDOUBLE_WORDS64(x,ix0,ix1);
  62. return (x);
  63. }