s_lround.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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, 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. long int
  20. lround (double x)
  21. {
  22. int32_t j0;
  23. u_int32_t i1, i0;
  24. long int result;
  25. int sign;
  26. EXTRACT_WORDS (i0, i1, x);
  27. j0 = ((i0 >> 20) & 0x7ff) - 0x3ff;
  28. sign = (i0 & 0x80000000) != 0 ? -1 : 1;
  29. i0 &= 0xfffff;
  30. i0 |= 0x100000;
  31. if (j0 < 20)
  32. {
  33. if (j0 < 0)
  34. return j0 < -1 ? 0 : sign;
  35. else
  36. {
  37. i0 += 0x80000 >> j0;
  38. result = i0 >> (20 - j0);
  39. }
  40. }
  41. else if (j0 < (int32_t) (8 * sizeof (long int)) - 1)
  42. {
  43. if (j0 >= 52)
  44. result = ((long int) i0 << (j0 - 20)) | (i1 << (j0 - 52));
  45. else
  46. {
  47. u_int32_t j = i1 + (0x80000000 >> (j0 - 20));
  48. if (j < i1)
  49. ++i0;
  50. if (j0 == 20)
  51. result = (long int) i0;
  52. else
  53. result = ((long int) i0 << (j0 - 20)) | (j >> (52 - j0));
  54. }
  55. }
  56. else
  57. {
  58. /* The number is too large. It is left implementation defined
  59. what happens. */
  60. return (long int) x;
  61. }
  62. return sign * result;
  63. }
  64. libm_hidden_def(lround)