s_llround.c 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /* Round double value to long long int.
  2. Copyright (C) 1997 Free Software Foundation, Inc.
  3. This file is part of the GNU C Library.
  4. Contributed by Ulrich Drepper <drepper@cygnus.com>, 1997.
  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. The GNU C Library is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. Lesser General Public License for more details.
  13. You should have received a copy of the GNU Lesser General Public
  14. License along with the GNU C Library; if not, write to the Free
  15. Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
  16. 02111-1307 USA. */
  17. #include <math.h>
  18. #include "math_private.h"
  19. libm_hidden_proto(llround)
  20. long long int
  21. llround (double x)
  22. {
  23. int32_t j0;
  24. u_int32_t i1, i0;
  25. long long int result;
  26. int sign;
  27. EXTRACT_WORDS (i0, i1, x);
  28. j0 = ((i0 >> 20) & 0x7ff) - 0x3ff;
  29. sign = (i0 & 0x80000000) != 0 ? -1 : 1;
  30. i0 &= 0xfffff;
  31. i0 |= 0x100000;
  32. if (j0 < 20)
  33. {
  34. if (j0 < 0)
  35. return j0 < -1 ? 0 : sign;
  36. else
  37. {
  38. i0 += 0x80000 >> j0;
  39. result = i0 >> (20 - j0);
  40. }
  41. }
  42. else if (j0 < (int32_t) (8 * sizeof (long long int)) - 1)
  43. {
  44. if (j0 >= 52)
  45. result = (((long long int) i0 << 32) | i1) << (j0 - 52);
  46. else
  47. {
  48. u_int32_t j = i1 + (0x80000000 >> (j0 - 20));
  49. if (j < i1)
  50. ++i0;
  51. if (j0 == 20)
  52. result = (long long int) i0;
  53. else
  54. result = ((long long int) i0 << (j0 - 20)) | (j >> (52 - j0));
  55. }
  56. }
  57. else
  58. {
  59. /* The number is too large. It is left implementation defined
  60. what happens. */
  61. return (long long int) x;
  62. }
  63. return sign * result;
  64. }
  65. libm_hidden_def(llround)