forked from libtom/libtomfloat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mpf_normalize.c
53 lines (47 loc) · 1.35 KB
/
mpf_normalize.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/* LibTomFloat, multiple-precision floating-point library
*
* LibTomFloat is a library that provides multiple-precision
* floating-point artihmetic as well as trigonometric functionality.
*
* This library requires the public domain LibTomMath to be installed.
*
* This library is free for all purposes without any express
* gurantee it works
*
* Tom St Denis, tomstdenis@iahu.ca, http://float.libtomcrypt.org
*/
#include <tomfloat.h>
int mpf_normalize(mp_float *a)
{
long cb, diff;
int err;
mp_digit c;
/* sanity */
if (a->radix < 2) {
return MP_VAL;
}
cb = mp_count_bits(&(a->mantissa));
if (cb > a->radix) {
diff = cb - a->radix;
a->exp += diff;
/* round it, add 1 after shift if diff-1'th bit is 1 */
c = a->mantissa.dp[diff/DIGIT_BIT] & (1U<<(diff%DIGIT_BIT));
if ((err = mp_div_2d(&(a->mantissa), diff, &(a->mantissa), NULL)) != MP_OKAY) {
return err;
}
if (c != 0) {
return mp_add_d(&(a->mantissa), 1, &(a->mantissa));
} else {
return MP_OKAY;
}
} else if (cb < a->radix) {
if (mp_iszero(&(a->mantissa)) == MP_YES) {
return mpf_const_0(a);
} else {
diff = a->radix - cb;
a->exp -= diff;
return mp_mul_2d(&(a->mantissa), diff, &(a->mantissa));
}
}
return MP_OKAY;
}