betomp.c 617 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. #include "os.h"
  2. #include <mp.h>
  3. #include "dat.h"
  4. // convert a big-endian byte array (most significant byte first) to an mpint
  5. mpint*
  6. betomp(uchar *p, uint n, mpint *b)
  7. {
  8. int m, s;
  9. mpdigit x;
  10. if(b == nil){
  11. b = mpnew(0);
  12. setmalloctag(b, getcallerpc(&p));
  13. }
  14. // dump leading zeros
  15. while(*p == 0 && n > 1){
  16. p++;
  17. n--;
  18. }
  19. // get the space
  20. mpbits(b, n*8);
  21. b->top = DIGITS(n*8);
  22. m = b->top-1;
  23. // first digit might not be Dbytes long
  24. s = ((n-1)*8)%Dbits;
  25. x = 0;
  26. for(; n > 0; n--){
  27. x |= ((mpdigit)(*p++)) << s;
  28. s -= 8;
  29. if(s < 0){
  30. b->p[m--] = x;
  31. s = Dbits-8;
  32. x = 0;
  33. }
  34. }
  35. return b;
  36. }