mpright.c 872 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. #include "os.h"
  2. #include <mp.h>
  3. #include "dat.h"
  4. // res = b >> shift
  5. void
  6. mpright(mpint *b, int shift, mpint *res)
  7. {
  8. int d, l, r, i;
  9. mpdigit this, last;
  10. res->sign = b->sign;
  11. if(b->top==0){
  12. res->top = 0;
  13. return;
  14. }
  15. // a negative right shift is a left shift
  16. if(shift < 0){
  17. mpleft(b, -shift, res);
  18. return;
  19. }
  20. if(res != b)
  21. mpbits(res, b->top*Dbits - shift);
  22. d = shift/Dbits;
  23. r = shift - d*Dbits;
  24. l = Dbits - r;
  25. // shift all the bits out == zero
  26. if(d>=b->top){
  27. res->top = 0;
  28. return;
  29. }
  30. // special case digit shifts
  31. if(r == 0){
  32. for(i = 0; i < b->top-d; i++)
  33. res->p[i] = b->p[i+d];
  34. } else {
  35. last = b->p[d];
  36. for(i = 0; i < b->top-d-1; i++){
  37. this = b->p[i+d+1];
  38. res->p[i] = (this<<l) | (last>>r);
  39. last = this;
  40. }
  41. res->p[i++] = last>>r;
  42. }
  43. while(i > 0 && res->p[i-1] == 0)
  44. i--;
  45. res->top = i;
  46. if(i==0)
  47. res->sign = 1;
  48. }