ntoab.c 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /* -*-comment-start: "//";comment-end:""-*-
  2. * GNU Mes --- Maxwell Equations of Software
  3. * Copyright © 2016,2017,2018,2019,2020 Jan (janneke) Nieuwenhuizen <janneke@gnu.org>
  4. *
  5. * This file is part of GNU Mes.
  6. *
  7. * GNU Mes is free software; you can redistribute it and/or modify it
  8. * under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 3 of the License, or (at
  10. * your option) any later version.
  11. *
  12. * GNU Mes is distributed in the hope that it will be useful, but
  13. * WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with GNU Mes. If not, see <http://www.gnu.org/licenses/>.
  19. */
  20. #include <mes/lib.h>
  21. #include <assert.h>
  22. #include <stdlib.h>
  23. #include <string.h>
  24. size_t
  25. __mesabi_uldiv (size_t a, size_t b, size_t *remainder)
  26. {
  27. remainder[0] = a % b;
  28. return a / b;
  29. }
  30. char *__itoa_buf;
  31. char *
  32. ntoab (long x, unsigned base, int signed_p)
  33. {
  34. if (__itoa_buf == 0)
  35. __itoa_buf = malloc (20);
  36. char *p = __itoa_buf + 11;
  37. p[0] = 0;
  38. p = p - 1;
  39. assert_msg (base > 0, "base > 0");
  40. int sign_p = 0;
  41. size_t i;
  42. size_t u;
  43. size_t b = base;
  44. if (signed_p != 0 && x < 0)
  45. {
  46. sign_p = 1;
  47. /* Avoid LONG_MIN */
  48. u = (-(x + 1));
  49. u = u + 1;
  50. }
  51. else
  52. u = x;
  53. do
  54. {
  55. u = __mesabi_uldiv (u, b, &i);
  56. if (i > 9)
  57. p[0] = 'a' + i - 10;
  58. else
  59. p[0] = '0' + i;
  60. p = p - 1;
  61. }
  62. while (u != 0);
  63. if (sign_p && p[1] != '0')
  64. {
  65. p[0] = '-';
  66. p = p - 1;
  67. }
  68. return p + 1;
  69. }