mptobe.c 879 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. #include "os.h"
  2. #include <mp.h>
  3. #include "dat.h"
  4. // convert an mpint into a big endian byte array (most significant byte first)
  5. // return number of bytes converted
  6. // if p == nil, allocate and result array
  7. int
  8. mptobe(mpint *b, uchar *p, uint n, uchar **pp)
  9. {
  10. int i, j, suppress;
  11. mpdigit x;
  12. uchar *e, *s, c;
  13. if(p == nil){
  14. n = (b->top+1)*Dbytes;
  15. p = malloc(n);
  16. }
  17. if(p == nil)
  18. return -1;
  19. if(pp != nil)
  20. *pp = p;
  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 1;
  28. }
  29. s = p;
  30. e = s+n;
  31. suppress = 1;
  32. for(i = b->top-1; i >= 0; i--){
  33. x = b->p[i];
  34. for(j = Dbits-8; j >= 0; j -= 8){
  35. c = x>>j;
  36. if(c == 0 && suppress)
  37. continue;
  38. if(p >= e)
  39. return -1;
  40. *p++ = c;
  41. suppress = 0;
  42. }
  43. }
  44. // guarantee at least one byte
  45. if(s == p){
  46. if(p >= e)
  47. return -1;
  48. *p++ = 0;
  49. }
  50. return p - s;
  51. }