bn_mp_read_radix.c 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. #include <tommath.h>
  2. #ifdef BN_MP_READ_RADIX_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. /* read a string [ASCII] in a given radix */
  18. int mp_read_radix (mp_int * a, const char *str, int radix)
  19. {
  20. int y, res, neg;
  21. char ch;
  22. /* zero the digit bignum */
  23. mp_zero(a);
  24. /* make sure the radix is ok */
  25. if (radix < 2 || radix > 64) {
  26. return MP_VAL;
  27. }
  28. /* if the leading digit is a
  29. * minus set the sign to negative.
  30. */
  31. if (*str == '-') {
  32. ++str;
  33. neg = MP_NEG;
  34. } else {
  35. neg = MP_ZPOS;
  36. }
  37. /* set the integer to the default of zero */
  38. mp_zero (a);
  39. /* process each digit of the string */
  40. while (*str) {
  41. /* if the radix < 36 the conversion is case insensitive
  42. * this allows numbers like 1AB and 1ab to represent the same value
  43. * [e.g. in hex]
  44. */
  45. ch = (char) ((radix < 36) ? toupper (*str) : *str);
  46. for (y = 0; y < 64; y++) {
  47. if (ch == mp_s_rmap[y]) {
  48. break;
  49. }
  50. }
  51. /* if the char was found in the map
  52. * and is less than the given radix add it
  53. * to the number, otherwise exit the loop.
  54. */
  55. if (y < radix) {
  56. if ((res = mp_mul_d (a, (mp_digit) radix, a)) != MP_OKAY) {
  57. return res;
  58. }
  59. if ((res = mp_add_d (a, (mp_digit) y, a)) != MP_OKAY) {
  60. return res;
  61. }
  62. } else {
  63. break;
  64. }
  65. ++str;
  66. }
  67. /* set the sign only if a != 0 */
  68. if (mp_iszero(a) != 1) {
  69. a->sign = neg;
  70. }
  71. return MP_OKAY;
  72. }
  73. #endif
  74. /* $Source: /cvs/libtom/libtommath/bn_mp_read_radix.c,v $ */
  75. /* $Revision: 1.4 $ */
  76. /* $Date: 2006/03/31 14:18:44 $ */