2020-12-28 21:40:37 +00:00
|
|
|
#include "tommath_private.h"
|
2014-12-10 21:56:49 +00:00
|
|
|
#ifdef BN_MP_SUB_C
|
2020-12-28 21:40:37 +00:00
|
|
|
/* LibTomMath, multiple-precision integer library -- Tom St Denis */
|
|
|
|
/* SPDX-License-Identifier: Unlicense */
|
2014-12-10 21:56:49 +00:00
|
|
|
|
|
|
|
/* high level subtraction (handles signs) */
|
2020-12-28 21:40:37 +00:00
|
|
|
mp_err mp_sub(const mp_int *a, const mp_int *b, mp_int *c)
|
2014-12-10 21:56:49 +00:00
|
|
|
{
|
2020-12-28 21:40:37 +00:00
|
|
|
mp_sign sa = a->sign, sb = b->sign;
|
|
|
|
mp_err err;
|
2014-12-10 21:56:49 +00:00
|
|
|
|
2020-12-28 21:40:37 +00:00
|
|
|
if (sa != sb) {
|
|
|
|
/* subtract a negative from a positive, OR */
|
|
|
|
/* subtract a positive from a negative. */
|
|
|
|
/* In either case, ADD their magnitudes, */
|
|
|
|
/* and use the sign of the first number. */
|
2014-12-10 21:56:49 +00:00
|
|
|
c->sign = sa;
|
2020-12-28 21:40:37 +00:00
|
|
|
err = s_mp_add(a, b, c);
|
|
|
|
} else {
|
|
|
|
/* subtract a positive from a positive, OR */
|
|
|
|
/* subtract a negative from a negative. */
|
|
|
|
/* First, take the difference between their */
|
|
|
|
/* magnitudes, then... */
|
|
|
|
if (mp_cmp_mag(a, b) != MP_LT) {
|
|
|
|
/* Copy the sign from the first */
|
|
|
|
c->sign = sa;
|
|
|
|
/* The first has a larger or equal magnitude */
|
|
|
|
err = s_mp_sub(a, b, c);
|
|
|
|
} else {
|
|
|
|
/* The result has the *opposite* sign from */
|
|
|
|
/* the first number. */
|
|
|
|
c->sign = (sa == MP_ZPOS) ? MP_NEG : MP_ZPOS;
|
|
|
|
/* The second has a larger magnitude */
|
|
|
|
err = s_mp_sub(b, a, c);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return err;
|
2014-12-10 21:56:49 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
#endif
|