bn_s_mp_sub.c 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. #include <tommath.h>
  2. #ifdef BN_S_MP_SUB_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. /* low level subtraction (assumes |a| > |b|), HAC pp.595 Algorithm 14.9 */
  18. int
  19. s_mp_sub (mp_int * a, mp_int * b, mp_int * c)
  20. {
  21. int olduse, res, min, max;
  22. /* find sizes */
  23. min = b->used;
  24. max = a->used;
  25. /* init result */
  26. if (c->alloc < max) {
  27. if ((res = mp_grow (c, max)) != MP_OKAY) {
  28. return res;
  29. }
  30. }
  31. olduse = c->used;
  32. c->used = max;
  33. {
  34. register mp_digit u, *tmpa, *tmpb, *tmpc;
  35. register int i;
  36. /* alias for digit pointers */
  37. tmpa = a->dp;
  38. tmpb = b->dp;
  39. tmpc = c->dp;
  40. /* set carry to zero */
  41. u = 0;
  42. for (i = 0; i < min; i++) {
  43. /* T[i] = A[i] - B[i] - U */
  44. *tmpc = *tmpa++ - *tmpb++ - u;
  45. /* U = carry bit of T[i]
  46. * Note this saves performing an AND operation since
  47. * if a carry does occur it will propagate all the way to the
  48. * MSB. As a result a single shift is enough to get the carry
  49. */
  50. u = *tmpc >> ((mp_digit)(CHAR_BIT * sizeof (mp_digit) - 1));
  51. /* Clear carry from T[i] */
  52. *tmpc++ &= MP_MASK;
  53. }
  54. /* now copy higher words if any, e.g. if A has more digits than B */
  55. for (; i < max; i++) {
  56. /* T[i] = A[i] - U */
  57. *tmpc = *tmpa++ - u;
  58. /* U = carry bit of T[i] */
  59. u = *tmpc >> ((mp_digit)(CHAR_BIT * sizeof (mp_digit) - 1));
  60. /* Clear carry from T[i] */
  61. *tmpc++ &= MP_MASK;
  62. }
  63. /* clear digits above used (since we may not have grown result above) */
  64. for (i = c->used; i < olduse; i++) {
  65. *tmpc++ = 0;
  66. }
  67. }
  68. mp_clamp (c);
  69. return MP_OKAY;
  70. }
  71. #endif
  72. /* $Source: /cvs/libtom/libtommath/bn_s_mp_sub.c,v $ */
  73. /* $Revision: 1.3 $ */
  74. /* $Date: 2006/03/31 14:18:44 $ */