2
|
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 /* b = a/2 */ |
|
18 int mp_div_2(mp_int * a, mp_int * b) |
|
19 { |
|
20 int x, res, oldused; |
|
21 |
|
22 /* copy */ |
|
23 if (b->alloc < a->used) { |
|
24 if ((res = mp_grow (b, a->used)) != MP_OKAY) { |
|
25 return res; |
|
26 } |
|
27 } |
|
28 |
|
29 oldused = b->used; |
|
30 b->used = a->used; |
|
31 { |
|
32 register mp_digit r, rr, *tmpa, *tmpb; |
|
33 |
|
34 /* source alias */ |
|
35 tmpa = a->dp + b->used - 1; |
|
36 |
|
37 /* dest alias */ |
|
38 tmpb = b->dp + b->used - 1; |
|
39 |
|
40 /* carry */ |
|
41 r = 0; |
|
42 for (x = b->used - 1; x >= 0; x--) { |
|
43 /* get the carry for the next iteration */ |
|
44 rr = *tmpa & 1; |
|
45 |
|
46 /* shift the current digit, add in carry and store */ |
|
47 *tmpb-- = (*tmpa-- >> 1) | (r << (DIGIT_BIT - 1)); |
|
48 |
|
49 /* forward carry to next iteration */ |
|
50 r = rr; |
|
51 } |
|
52 |
|
53 /* zero excess digits */ |
|
54 tmpb = b->dp + b->used; |
|
55 for (x = b->used; x < oldused; x++) { |
|
56 *tmpb++ = 0; |
|
57 } |
|
58 } |
|
59 b->sign = a->sign; |
|
60 mp_clamp (b); |
|
61 return MP_OKAY; |
|
62 } |