/
Int64.c
139 lines (125 loc) · 2.33 KB
/
Int64.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
#include "Int64.h"
int sign (Int64 num)
{
if (num.hi < 0)
return -1;
else if ((num.hi == 0) && (num.low == 0))
return 0;
else
return 1;
}
Int64 neg (Int64 num)
{
if (num.low == 0)
num.hi = -num.hi;
else
{
num.low = ~num.low + 1;
num.hi = ~num.hi;
}
return num;
}
Int64 Int64_plus (Int64 left, Int64 right)
{
Int64 ret;
ret.low = 0;
ret.hi = left.hi;
ret.low = left.low + right.low;
if ((unsigned int)ret.low < (unsigned int)right.low)
++ret.hi;
ret.hi += right.hi;
return ret;
}
Int64 Int64_minus (Int64 left, Int64 right)
{
return Int64_plus(left, neg(right));
}
Int64 Int64_multi (Int64 left, Int64 right)
{
int s = sign(right);
Int64 bin;
int i;
if (s == 0)
{
left.hi = left.low = 0;
return left;
}
else if (sign(left) == 0)
return left;
if (s < 0)
right = neg(right);
if (sign(left) < 0)
{
bin = neg(left);
s = -s;
}
else
bin = left;
left.hi = left.low = 0;
for (i = 0; i < 32; ++i, right.low >>= 1, bin = Int64_plus(bin, bin))
if ((right.low & 1) != 0)
left = Int64_plus(left, bin);
for (i = 0; i < 32; ++i, right.hi >>= 1, bin = Int64_plus(bin, bin))
if ((right.hi & 1) != 0)
left = Int64_plus(left, bin);
if (s < 0)
left = neg(left);
return left;
}
int N_less (Int64 *left, Int64 *right)
{
if (left->hi < right->hi)
return 1;
else if ((left->hi == right->hi)
&& ((unsigned int)left->low < (unsigned int)right->low))
return 1;
else
return 0;
}
void N_div_2 (Int64 *num)
{
num->low = (unsigned int)num->low >> 1;
if (num->hi & 1)
num->low |= 0x80000000;
num->hi = (unsigned int)num->hi >> 1;
}
Int64 Int64_div (Int64 left, Int64 right)
{
int s = sign(right);
Int64 bin;
int t = 0;
Int64 one;
one.low = 1;one.hi = 0;
if (s == 0)
return right;
else if (sign(left) == 0)
return left;
if (s < 0)
right = neg(right);
if (sign(left) < 0)
{
bin = neg(left);
s = -s;
}
else
bin = left;
left.low = left.hi = 0;
while (!N_less (&bin, &right))
{
++t;
right = Int64_plus(right, right);
}
for (; t > 0; --t)
{
N_div_2(&right);
left = Int64_plus(left, left);
if (!N_less (&bin, &right))
{
bin = Int64_minus(bin, right);
left = Int64_plus(left, one);
}
}
if (s < 0)
left = neg(left);
return left;
}