comparison bn_mp_div_2d.c @ 2:86e0b50a9b58 libtommath-orig ltm-0.30-orig

ltm 0.30 orig import
author Matt Johnston <matt@ucc.asn.au>
date Mon, 31 May 2004 18:25:22 +0000
parents
children d29b64170cf0
comparison
equal deleted inserted replaced
-1:000000000000 2:86e0b50a9b58
1 /* LibTomMath, multiple-precision integer library -- Tom St Denis
2 *
3 * LibTomMath is a library that provides multiple-precision
4 * integer arithmetic as well as number theoretic functionality.
5 *
6 * The library was designed directly after the MPI library by
7 * Michael Fromberger but has been written from scratch with
8 * additional optimizations in place.
9 *
10 * The library is free for all purposes without any express
11 * guarantee it works.
12 *
13 * Tom St Denis, [email protected], http://math.libtomcrypt.org
14 */
15 #include <tommath.h>
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
24
25 /* if the shift count is <= 0 then we do no work */
26 if (b <= 0) {
27 res = mp_copy (a, c);
28 if (d != NULL) {
29 mp_zero (d);
30 }
31 return res;
32 }
33
34 if ((res = mp_init (&t)) != MP_OKAY) {
35 return res;
36 }
37
38 /* get the remainder */
39 if (d != NULL) {
40 if ((res = mp_mod_2d (a, b, &t)) != MP_OKAY) {
41 mp_clear (&t);
42 return res;
43 }
44 }
45
46 /* copy */
47 if ((res = mp_copy (a, c)) != MP_OKAY) {
48 mp_clear (&t);
49 return res;
50 }
51
52 /* shift by as many digits in the bit count */
53 if (b >= (int)DIGIT_BIT) {
54 mp_rshd (c, b / DIGIT_BIT);
55 }
56
57 /* shift any bit count < DIGIT_BIT */
58 D = (mp_digit) (b % DIGIT_BIT);
59 if (D != 0) {
60 register mp_digit *tmpc, mask, shift;
61
62 /* mask */
63 mask = (((mp_digit)1) << D) - 1;
64
65 /* shift for lsb */
66 shift = DIGIT_BIT - D;
67
68 /* alias */
69 tmpc = c->dp + (c->used - 1);
70
71 /* carry */
72 r = 0;
73 for (x = c->used - 1; x >= 0; x--) {
74 /* get the lower bits of this word in a temp */
75 rr = *tmpc & mask;
76
77 /* shift the current word and mix in the carry bits from the previous word */
78 *tmpc = (*tmpc >> D) | (r << shift);
79 --tmpc;
80
81 /* set the carry to the carry bits of the current word found above */
82 r = rr;
83 }
84 }
85 mp_clamp (c);
86 if (d != NULL) {
87 mp_exch (&t, d);
88 }
89 mp_clear (&t);
90 return MP_OKAY;
91 }