betomp.c 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. /*
  2. * This file is part of the UCB release of Plan 9. It is subject to the license
  3. * terms in the LICENSE file found in the top-level directory of this
  4. * distribution and at http://akaros.cs.berkeley.edu/files/Plan9License. No
  5. * part of the UCB release of Plan 9, including this file, may be copied,
  6. * modified, propagated, or distributed except according to the terms contained
  7. * in the LICENSE file.
  8. */
  9. #include "os.h"
  10. #include <mp.h>
  11. #include "dat.h"
  12. // convert a big-endian byte array (most significant byte first) to an mpint
  13. mpint*
  14. betomp(uint8_t *p, uint n, mpint *b)
  15. {
  16. int m, s;
  17. mpdigit x;
  18. if(b == nil){
  19. b = mpnew(0);
  20. setmalloctag(b, getcallerpc());
  21. }
  22. // dump leading zeros
  23. while(*p == 0 && n > 1){
  24. p++;
  25. n--;
  26. }
  27. // get the space
  28. mpbits(b, n*8);
  29. b->top = DIGITS(n*8);
  30. m = b->top-1;
  31. // first digit might not be Dbytes long
  32. s = ((n-1)*8)%Dbits;
  33. x = 0;
  34. for(; n > 0; n--){
  35. x |= ((mpdigit)(*p++)) << s;
  36. s -= 8;
  37. if(s < 0){
  38. b->p[m--] = x;
  39. s = Dbits-8;
  40. x = 0;
  41. }
  42. }
  43. return b;
  44. }