bn_mp_div_2.c 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. #include <tommath.h>
  2. #ifdef BN_MP_DIV_2_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. /* b = a/2 */
  18. int mp_div_2(mp_int * a, mp_int * b)
  19. {
  20. int x, res, oldused;
  21. /* copy */
  22. if (b->alloc < a->used) {
  23. if ((res = mp_grow (b, a->used)) != MP_OKAY) {
  24. return res;
  25. }
  26. }
  27. oldused = b->used;
  28. b->used = a->used;
  29. {
  30. register mp_digit r, rr, *tmpa, *tmpb;
  31. /* source alias */
  32. tmpa = a->dp + b->used - 1;
  33. /* dest alias */
  34. tmpb = b->dp + b->used - 1;
  35. /* carry */
  36. r = 0;
  37. for (x = b->used - 1; x >= 0; x--) {
  38. /* get the carry for the next iteration */
  39. rr = *tmpa & 1;
  40. /* shift the current digit, add in carry and store */
  41. *tmpb-- = (*tmpa-- >> 1) | (r << (DIGIT_BIT - 1));
  42. /* forward carry to next iteration */
  43. r = rr;
  44. }
  45. /* zero excess digits */
  46. tmpb = b->dp + b->used;
  47. for (x = b->used; x < oldused; x++) {
  48. *tmpb++ = 0;
  49. }
  50. }
  51. b->sign = a->sign;
  52. mp_clamp (b);
  53. return MP_OKAY;
  54. }
  55. #endif
  56. /* $Source: /cvs/libtom/libtommath/bn_mp_div_2.c,v $ */
  57. /* $Revision: 1.3 $ */
  58. /* $Date: 2006/03/31 14:18:44 $ */