bn_mp_div_2d.c 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #include "tommath_private.h"
  2. #ifdef BN_MP_DIV_2D_C
  3. /* LibTomMath, multiple-precision integer library -- Tom St Denis */
  4. /* SPDX-License-Identifier: Unlicense */
  5. /* shift right by a certain bit count (store quotient in c, optional remainder in d) */
  6. mp_err mp_div_2d(const mp_int *a, int b, mp_int *c, mp_int *d)
  7. {
  8. mp_digit D, r, rr;
  9. int x;
  10. mp_err err;
  11. /* if the shift count is <= 0 then we do no work */
  12. if (b <= 0) {
  13. err = mp_copy(a, c);
  14. if (d != NULL) {
  15. mp_zero(d);
  16. }
  17. return err;
  18. }
  19. /* copy */
  20. if ((err = mp_copy(a, c)) != MP_OKAY) {
  21. return err;
  22. }
  23. /* 'a' should not be used after here - it might be the same as d */
  24. /* get the remainder */
  25. if (d != NULL) {
  26. if ((err = mp_mod_2d(a, b, d)) != MP_OKAY) {
  27. return err;
  28. }
  29. }
  30. /* shift by as many digits in the bit count */
  31. if (b >= MP_DIGIT_BIT) {
  32. mp_rshd(c, b / MP_DIGIT_BIT);
  33. }
  34. /* shift any bit count < MP_DIGIT_BIT */
  35. D = (mp_digit)(b % MP_DIGIT_BIT);
  36. if (D != 0u) {
  37. mp_digit *tmpc, mask, shift;
  38. /* mask */
  39. mask = ((mp_digit)1 << D) - 1uL;
  40. /* shift for lsb */
  41. shift = (mp_digit)MP_DIGIT_BIT - D;
  42. /* alias */
  43. tmpc = c->dp + (c->used - 1);
  44. /* carry */
  45. r = 0;
  46. for (x = c->used - 1; x >= 0; x--) {
  47. /* get the lower bits of this word in a temp */
  48. rr = *tmpc & mask;
  49. /* shift the current word and mix in the carry bits from the previous word */
  50. *tmpc = (*tmpc >> D) | (r << shift);
  51. --tmpc;
  52. /* set the carry to the carry bits of the current word found above */
  53. r = rr;
  54. }
  55. }
  56. mp_clamp(c);
  57. return MP_OKAY;
  58. }
  59. #endif