division.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /*
  2. * GRUB -- GRand Unified Bootloader
  3. * Copyright (C) 2015 Free Software Foundation, Inc.
  4. *
  5. * GRUB is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * GRUB is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with GRUB. If not, see <http://www.gnu.org/licenses/>.
  17. */
  18. #include <grub/misc.h>
  19. #include <grub/dl.h>
  20. GRUB_MOD_LICENSE ("GPLv3+");
  21. static grub_uint64_t
  22. abs64(grub_int64_t a)
  23. {
  24. return a > 0 ? a : -a;
  25. }
  26. grub_int64_t
  27. grub_divmod64s (grub_int64_t n,
  28. grub_int64_t d,
  29. grub_int64_t *ro)
  30. {
  31. grub_uint64_t ru;
  32. grub_int64_t q, r;
  33. q = grub_divmod64 (abs64(n), abs64(d), &ru);
  34. r = ru;
  35. /* Now: |n| = |d| * q + r */
  36. if (n < 0)
  37. {
  38. /* -|n| = |d| * (-q) + (-r) */
  39. q = -q;
  40. r = -r;
  41. }
  42. /* Now: n = |d| * q + r */
  43. if (d < 0)
  44. {
  45. /* n = (-|d|) * (-q) + r */
  46. q = -q;
  47. }
  48. /* Now: n = d * q + r */
  49. if (ro)
  50. *ro = r;
  51. return q;
  52. }
  53. grub_uint32_t
  54. grub_divmod32 (grub_uint32_t n, grub_uint32_t d, grub_uint32_t *ro)
  55. {
  56. grub_uint64_t q, r;
  57. q = grub_divmod64 (n, d, &r);
  58. *ro = r;
  59. return q;
  60. }
  61. grub_int32_t
  62. grub_divmod32s (grub_int32_t n, grub_int32_t d, grub_int32_t *ro)
  63. {
  64. grub_int64_t q, r;
  65. q = grub_divmod64s (n, d, &r);
  66. *ro = r;
  67. return q;
  68. }