bn_mp_fread.c 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. #include "tommath_private.h"
  2. #ifdef BN_MP_FREAD_C
  3. /* LibTomMath, multiple-precision integer library -- Tom St Denis */
  4. /* SPDX-License-Identifier: Unlicense */
  5. #ifndef MP_NO_FILE
  6. /* read a bigint from a file stream in ASCII */
  7. mp_err mp_fread(mp_int *a, int radix, FILE *stream)
  8. {
  9. mp_err err;
  10. mp_sign neg;
  11. /* if first digit is - then set negative */
  12. int ch = fgetc(stream);
  13. if (ch == (int)'-') {
  14. neg = MP_NEG;
  15. ch = fgetc(stream);
  16. } else {
  17. neg = MP_ZPOS;
  18. }
  19. /* no digits, return error */
  20. if (ch == EOF) {
  21. return MP_ERR;
  22. }
  23. /* clear a */
  24. mp_zero(a);
  25. do {
  26. int y;
  27. unsigned pos = (unsigned)(ch - (int)'(');
  28. if (mp_s_rmap_reverse_sz < pos) {
  29. break;
  30. }
  31. y = (int)mp_s_rmap_reverse[pos];
  32. if ((y == 0xff) || (y >= radix)) {
  33. break;
  34. }
  35. /* shift up and add */
  36. if ((err = mp_mul_d(a, (mp_digit)radix, a)) != MP_OKAY) {
  37. return err;
  38. }
  39. if ((err = mp_add_d(a, (mp_digit)y, a)) != MP_OKAY) {
  40. return err;
  41. }
  42. } while ((ch = fgetc(stream)) != EOF);
  43. if (a->used != 0) {
  44. a->sign = neg;
  45. }
  46. return MP_OKAY;
  47. }
  48. #endif
  49. #endif