bn_mp_sub.c 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. #include <tommath.h>
  2. #ifdef BN_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. /* high level subtraction (handles signs) */
  18. int
  19. mp_sub (mp_int * a, mp_int * b, mp_int * c)
  20. {
  21. int sa, sb, res;
  22. sa = a->sign;
  23. sb = b->sign;
  24. if (sa != sb) {
  25. /* subtract a negative from a positive, OR */
  26. /* subtract a positive from a negative. */
  27. /* In either case, ADD their magnitudes, */
  28. /* and use the sign of the first number. */
  29. c->sign = sa;
  30. res = s_mp_add (a, b, c);
  31. } else {
  32. /* subtract a positive from a positive, OR */
  33. /* subtract a negative from a negative. */
  34. /* First, take the difference between their */
  35. /* magnitudes, then... */
  36. if (mp_cmp_mag (a, b) != MP_LT) {
  37. /* Copy the sign from the first */
  38. c->sign = sa;
  39. /* The first has a larger or equal magnitude */
  40. res = s_mp_sub (a, b, c);
  41. } else {
  42. /* The result has the *opposite* sign from */
  43. /* the first number. */
  44. c->sign = (sa == MP_ZPOS) ? MP_NEG : MP_ZPOS;
  45. /* The second has a larger magnitude */
  46. res = s_mp_sub (b, a, c);
  47. }
  48. }
  49. return res;
  50. }
  51. #endif
  52. /* $Source: /cvs/libtom/libtommath/bn_mp_sub.c,v $ */
  53. /* $Revision: 1.3 $ */
  54. /* $Date: 2006/03/31 14:18:44 $ */