s_lround.c 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /* Round double value to long int.
  2. Copyright (C) 1997, 2004 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, see
  15. <http://www.gnu.org/licenses/>. */
  16. #include <math.h>
  17. #include "math_private.h"
  18. long int
  19. lround (double x)
  20. {
  21. int32_t _j0;
  22. u_int32_t i1, i0;
  23. long int result;
  24. int sign;
  25. EXTRACT_WORDS (i0, i1, x);
  26. _j0 = ((i0 >> 20) & 0x7ff) - 0x3ff;
  27. sign = (i0 & 0x80000000) != 0 ? -1 : 1;
  28. i0 &= 0xfffff;
  29. i0 |= 0x100000;
  30. if (_j0 < 20)
  31. {
  32. if (_j0 < 0)
  33. return _j0 < -1 ? 0 : sign;
  34. else
  35. {
  36. i0 += 0x80000 >> _j0;
  37. result = i0 >> (20 - _j0);
  38. }
  39. }
  40. else if (_j0 < (int32_t) (8 * sizeof (long int)) - 1)
  41. {
  42. if (_j0 >= 52)
  43. result = ((long int) i0 << (_j0 - 20)) | (i1 << (_j0 - 52));
  44. else
  45. {
  46. u_int32_t j = i1 + (0x80000000 >> (_j0 - 20));
  47. if (j < i1)
  48. ++i0;
  49. if (_j0 == 20)
  50. result = (long int) i0;
  51. else
  52. result = ((long int) i0 << (_j0 - 20)) | (j >> (52 - _j0));
  53. }
  54. }
  55. else
  56. {
  57. /* The number is too large. It is left implementation defined
  58. what happens. */
  59. return (long int) x;
  60. }
  61. return sign * result;
  62. }
  63. libm_hidden_def(lround)