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 /* shift left by a certain bit count */ |
|
18 int mp_mul_2d (mp_int * a, int b, mp_int * c) |
|
19 { |
|
20 mp_digit d; |
|
21 int res; |
|
22 |
|
23 /* copy */ |
|
24 if (a != c) { |
|
25 if ((res = mp_copy (a, c)) != MP_OKAY) { |
|
26 return res; |
|
27 } |
|
28 } |
|
29 |
|
30 if (c->alloc < (int)(c->used + b/DIGIT_BIT + 1)) { |
|
31 if ((res = mp_grow (c, c->used + b / DIGIT_BIT + 1)) != MP_OKAY) { |
|
32 return res; |
|
33 } |
|
34 } |
|
35 |
|
36 /* shift by as many digits in the bit count */ |
|
37 if (b >= (int)DIGIT_BIT) { |
|
38 if ((res = mp_lshd (c, b / DIGIT_BIT)) != MP_OKAY) { |
|
39 return res; |
|
40 } |
|
41 } |
|
42 |
|
43 /* shift any bit count < DIGIT_BIT */ |
|
44 d = (mp_digit) (b % DIGIT_BIT); |
|
45 if (d != 0) { |
|
46 register mp_digit *tmpc, shift, mask, r, rr; |
|
47 register int x; |
|
48 |
|
49 /* bitmask for carries */ |
|
50 mask = (((mp_digit)1) << d) - 1; |
|
51 |
|
52 /* shift for msbs */ |
|
53 shift = DIGIT_BIT - d; |
|
54 |
|
55 /* alias */ |
|
56 tmpc = c->dp; |
|
57 |
|
58 /* carry */ |
|
59 r = 0; |
|
60 for (x = 0; x < c->used; x++) { |
|
61 /* get the higher bits of the current word */ |
|
62 rr = (*tmpc >> shift) & mask; |
|
63 |
|
64 /* shift the current word and OR in the carry */ |
|
65 *tmpc = ((*tmpc << d) | r) & MP_MASK; |
|
66 ++tmpc; |
|
67 |
|
68 /* set the carry to the carry bits of the current word */ |
|
69 r = rr; |
|
70 } |
|
71 |
|
72 /* set final carry */ |
|
73 if (r != 0) { |
|
74 c->dp[(c->used)++] = r; |
|
75 } |
|
76 } |
|
77 mp_clamp (c); |
|
78 return MP_OKAY; |
|
79 } |