bn_mp_toradix.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. #include <tommath.h>
  2. #ifdef BN_MP_TORADIX_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. int mp_toradix (mp_int * a, char *str, int radix)
  19. {
  20. int res, digs;
  21. mp_int t;
  22. mp_digit d;
  23. char *_s = str;
  24. /* check range of the radix */
  25. if (radix < 2 || radix > 64) {
  26. return MP_VAL;
  27. }
  28. /* quick out if its zero */
  29. if (mp_iszero(a) == 1) {
  30. *str++ = '0';
  31. *str = '\0';
  32. return MP_OKAY;
  33. }
  34. if ((res = mp_init_copy (&t, a)) != MP_OKAY) {
  35. return res;
  36. }
  37. /* if it is negative output a - */
  38. if (t.sign == MP_NEG) {
  39. ++_s;
  40. *str++ = '-';
  41. t.sign = MP_ZPOS;
  42. }
  43. digs = 0;
  44. while (mp_iszero (&t) == 0) {
  45. if ((res = mp_div_d (&t, (mp_digit) radix, &t, &d)) != MP_OKAY) {
  46. mp_clear (&t);
  47. return res;
  48. }
  49. *str++ = mp_s_rmap[d];
  50. ++digs;
  51. }
  52. /* reverse the digits of the string. In this case _s points
  53. * to the first digit [exluding the sign] of the number]
  54. */
  55. bn_reverse ((unsigned char *)_s, digs);
  56. /* append a NULL so the string is properly terminated */
  57. *str = '\0';
  58. mp_clear (&t);
  59. return MP_OKAY;
  60. }
  61. #endif
  62. /* $Source: /cvs/libtom/libtommath/bn_mp_toradix.c,v $ */
  63. /* $Revision: 1.3 $ */
  64. /* $Date: 2006/03/31 14:18:44 $ */