bn_mp_toradix_n.c 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. #include <tommath.h>
  2. #ifdef BN_MP_TORADIX_N_C
  3. /* LibTomMath, multiple-precision integer library -- Tom St Denis
  4. *
  5. * LibTomMath is a library that provides multiple-precision
  6. * integer arithmetic as well as number theoretic functionality.
  7. *
  8. * The library was designed directly after the MPI library by
  9. * Michael Fromberger but has been written from scratch with
  10. * additional optimizations in place.
  11. *
  12. * The library is free for all purposes without any express
  13. * guarantee it works.
  14. *
  15. * Tom St Denis, tomstdenis@gmail.com, http://math.libtomcrypt.com
  16. */
  17. /* stores a bignum as a ASCII string in a given radix (2..64)
  18. *
  19. * Stores upto maxlen-1 chars and always a NULL byte
  20. */
  21. int mp_toradix_n(mp_int * a, char *str, int radix, int maxlen)
  22. {
  23. int res, digs;
  24. mp_int t;
  25. mp_digit d;
  26. char *_s = str;
  27. /* check range of the maxlen, radix */
  28. if (maxlen < 2 || radix < 2 || radix > 64) {
  29. return MP_VAL;
  30. }
  31. /* quick out if its zero */
  32. if (mp_iszero(a) == MP_YES) {
  33. *str++ = '0';
  34. *str = '\0';
  35. return MP_OKAY;
  36. }
  37. if ((res = mp_init_copy (&t, a)) != MP_OKAY) {
  38. return res;
  39. }
  40. /* if it is negative output a - */
  41. if (t.sign == MP_NEG) {
  42. /* we have to reverse our digits later... but not the - sign!! */
  43. ++_s;
  44. /* store the flag and mark the number as positive */
  45. *str++ = '-';
  46. t.sign = MP_ZPOS;
  47. /* subtract a char */
  48. --maxlen;
  49. }
  50. digs = 0;
  51. while (mp_iszero (&t) == 0) {
  52. if (--maxlen < 1) {
  53. /* no more room */
  54. break;
  55. }
  56. if ((res = mp_div_d (&t, (mp_digit) radix, &t, &d)) != MP_OKAY) {
  57. mp_clear (&t);
  58. return res;
  59. }
  60. *str++ = mp_s_rmap[d];
  61. ++digs;
  62. }
  63. /* reverse the digits of the string. In this case _s points
  64. * to the first digit [exluding the sign] of the number
  65. */
  66. bn_reverse ((unsigned char *)_s, digs);
  67. /* append a NULL so the string is properly terminated */
  68. *str = '\0';
  69. mp_clear (&t);
  70. return MP_OKAY;
  71. }
  72. #endif
  73. /* $Source: /cvs/libtom/libtommath/bn_mp_toradix_n.c,v $ */
  74. /* $Revision: 1.4 $ */
  75. /* $Date: 2006/03/31 14:18:44 $ */