bn_mp_to_radix.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. #include "tommath_private.h"
  2. #ifdef BN_MP_TO_RADIX_C
  3. /* LibTomMath, multiple-precision integer library -- Tom St Denis */
  4. /* SPDX-License-Identifier: Unlicense */
  5. /* stores a bignum as a ASCII string in a given radix (2..64)
  6. *
  7. * Stores upto "size - 1" chars and always a NULL byte, puts the number of characters
  8. * written, including the '\0', in "written".
  9. */
  10. mp_err mp_to_radix(const mp_int *a, char *str, size_t maxlen, size_t *written, int radix)
  11. {
  12. size_t digs;
  13. mp_err err;
  14. mp_int t;
  15. mp_digit d;
  16. char *_s = str;
  17. /* check range of radix and size*/
  18. if (maxlen < 2u) {
  19. return MP_BUF;
  20. }
  21. if ((radix < 2) || (radix > 64)) {
  22. return MP_VAL;
  23. }
  24. /* quick out if its zero */
  25. if (MP_IS_ZERO(a)) {
  26. *str++ = '0';
  27. *str = '\0';
  28. if (written != NULL) {
  29. *written = 2u;
  30. }
  31. return MP_OKAY;
  32. }
  33. if ((err = mp_init_copy(&t, a)) != MP_OKAY) {
  34. return err;
  35. }
  36. /* if it is negative output a - */
  37. if (t.sign == MP_NEG) {
  38. /* we have to reverse our digits later... but not the - sign!! */
  39. ++_s;
  40. /* store the flag and mark the number as positive */
  41. *str++ = '-';
  42. t.sign = MP_ZPOS;
  43. /* subtract a char */
  44. --maxlen;
  45. }
  46. digs = 0u;
  47. while (!MP_IS_ZERO(&t)) {
  48. if (--maxlen < 1u) {
  49. /* no more room */
  50. err = MP_BUF;
  51. goto LBL_ERR;
  52. }
  53. if ((err = mp_div_d(&t, (mp_digit)radix, &t, &d)) != MP_OKAY) {
  54. goto LBL_ERR;
  55. }
  56. *str++ = mp_s_rmap[d];
  57. ++digs;
  58. }
  59. /* reverse the digits of the string. In this case _s points
  60. * to the first digit [exluding the sign] of the number
  61. */
  62. s_mp_reverse((unsigned char *)_s, digs);
  63. /* append a NULL so the string is properly terminated */
  64. *str = '\0';
  65. digs++;
  66. if (written != NULL) {
  67. *written = (a->sign == MP_NEG) ? (digs + 1u): digs;
  68. }
  69. LBL_ERR:
  70. mp_clear(&t);
  71. return err;
  72. }
  73. #endif