mptole.c 786 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. #include "os.h"
  2. #include <mp.h>
  3. #include "dat.h"
  4. // convert an mpint into a little endian byte array (least significant byte first)
  5. // return number of bytes converted
  6. // if p == nil, allocate and result array
  7. int
  8. mptole(mpint *b, uchar *p, uint n, uchar **pp)
  9. {
  10. int i, j;
  11. mpdigit x;
  12. uchar *e, *s;
  13. if(p == nil){
  14. n = (b->top+1)*Dbytes;
  15. p = malloc(n);
  16. }
  17. if(pp != nil)
  18. *pp = p;
  19. if(p == nil)
  20. return -1;
  21. memset(p, 0, n);
  22. // special case 0
  23. if(b->top == 0){
  24. if(n < 1)
  25. return -1;
  26. else
  27. return 0;
  28. }
  29. s = p;
  30. e = s+n;
  31. for(i = 0; i < b->top-1; i++){
  32. x = b->p[i];
  33. for(j = 0; j < Dbytes; j++){
  34. if(p >= e)
  35. return -1;
  36. *p++ = x;
  37. x >>= 8;
  38. }
  39. }
  40. x = b->p[i];
  41. while(x > 0){
  42. if(p >= e)
  43. return -1;
  44. *p++ = x;
  45. x >>= 8;
  46. }
  47. return p - s;
  48. }