bn_mp_div_2d.c 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. #include <tommath.h>
  2. #ifdef BN_MP_DIV_2D_C
  3. /* LibTomMath, multiple-precision integer library -- Tom St Denis
  4. *
  5. * LibTomMath is a library that provides multiple-precision
  6. * integer arithmetic as well as number theoretic functionality.
  7. *
  8. * The library was designed directly after the MPI library by
  9. * Michael Fromberger but has been written from scratch with
  10. * additional optimizations in place.
  11. *
  12. * The library is free for all purposes without any express
  13. * guarantee it works.
  14. *
  15. * Tom St Denis, tomstdenis@gmail.com, http://math.libtomcrypt.com
  16. */
  17. /* shift right by a certain bit count (store quotient in c, optional remainder in d) */
  18. int mp_div_2d (mp_int * a, int b, mp_int * c, mp_int * d)
  19. {
  20. mp_digit D, r, rr;
  21. int x, res;
  22. mp_int t;
  23. /* if the shift count is <= 0 then we do no work */
  24. if (b <= 0) {
  25. res = mp_copy (a, c);
  26. if (d != NULL) {
  27. mp_zero (d);
  28. }
  29. return res;
  30. }
  31. if ((res = mp_init (&t)) != MP_OKAY) {
  32. return res;
  33. }
  34. /* get the remainder */
  35. if (d != NULL) {
  36. if ((res = mp_mod_2d (a, b, &t)) != MP_OKAY) {
  37. mp_clear (&t);
  38. return res;
  39. }
  40. }
  41. /* copy */
  42. if ((res = mp_copy (a, c)) != MP_OKAY) {
  43. mp_clear (&t);
  44. return res;
  45. }
  46. /* shift by as many digits in the bit count */
  47. if (b >= (int)DIGIT_BIT) {
  48. mp_rshd (c, b / DIGIT_BIT);
  49. }
  50. /* shift any bit count < DIGIT_BIT */
  51. D = (mp_digit) (b % DIGIT_BIT);
  52. if (D != 0) {
  53. register mp_digit *tmpc, mask, shift;
  54. /* mask */
  55. mask = (((mp_digit)1) << D) - 1;
  56. /* shift for lsb */
  57. shift = DIGIT_BIT - D;
  58. /* alias */
  59. tmpc = c->dp + (c->used - 1);
  60. /* carry */
  61. r = 0;
  62. for (x = c->used - 1; x >= 0; x--) {
  63. /* get the lower bits of this word in a temp */
  64. rr = *tmpc & mask;
  65. /* shift the current word and mix in the carry bits from the previous word */
  66. *tmpc = (*tmpc >> D) | (r << shift);
  67. --tmpc;
  68. /* set the carry to the carry bits of the current word found above */
  69. r = rr;
  70. }
  71. }
  72. mp_clamp (c);
  73. if (d != NULL) {
  74. mp_exch (&t, d);
  75. }
  76. mp_clear (&t);
  77. return MP_OKAY;
  78. }
  79. #endif
  80. /* $Source: /cvs/libtom/libtommath/bn_mp_div_2d.c,v $ */
  81. /* $Revision: 1.3 $ */
  82. /* $Date: 2006/03/31 14:18:44 $ */