blob: c337a34251dbf87f3f6f07662f89c3edd883ffd6 (
plain)
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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
|
#include <iomanip>
#include <sstream>
#include "number.h"
number::number(std::uint32_t n):
_operands{n}
{ }
/* Type Conversion {{{ */
std::string
number::to_hex_string() const
{
if (_operands.empty()) {
return std::string("0x0");
}
std::ostringstream ss;
ss << "0x" << std::hex;
for (auto it = _operands.crbegin(); it != _operands.crend(); ++it) {
ss << *it;
/* If more operands are present, successive ones must be padded. */
ss << std::setfill('0');
ss << std::setw(8);
}
return ss.str();
}
std::string
number::to_dec_string() const
{
if (_operands.empty()) {
return std::string("0");
}
std::ostringstream ss;
ss << std::dec;
if (_operands.size() == 1) {
ss << _operands.front();
} else {
/* TODO */
ss << "[Not implemented]";
}
return ss.str();
}
/* }}} */
/* Operations {{{ */
number
number::operator+(const number &n) const
{
/* We make sure our object is greater than or equal to n. */
if (*this < n) {
return n.operator+(*this);
}
number result;
auto it = _operands.cbegin();
auto it_n = n._operands.cbegin();
bool carry = false;
while (it != _operands.cend()) {
const auto n1 = *it;
const auto n2 = *it_n;
result._operands.push_back(n1 + n2 + (carry ? 1 : 0));
if (carry && (n1 == UINT32_MAX)) {
carry = true;
} else {
carry = ((UINT32_MAX - n1 - (carry ? 1 : 0)) < n2);
}
++it;
++it_n;
}
if (carry) {
result._operands.push_back(1);
}
return result;
}
/* }}} */
/* Comparison operators {{{ */
bool
number::operator<(const number &n) const
{
const auto size = this->_operands.size();
if (size < n._operands.size()) {
return true;
}
if (size > n._operands.size()) {
return false;
}
/* Because first item is the least significant. */
auto l1(this->_operands);
auto l2(n._operands);
l1.reverse();
l2.reverse();
return l1 < l2;
}
bool
number::operator>(const number &n) const
{
return n.operator<(*this);
}
bool
number::operator<=(const number &n) const
{
return operator<(n) || operator==(n);
}
bool
number::operator>=(const number &n) const
{
return operator>(n) || operator==(n);
}
bool
number::operator==(const number &n) const
{
return _operands == n._operands;
}
bool
number::operator!=(const number &n) const
{
return _operands != n._operands;
}
/* }}} */
std::ostream &
operator<<(std::ostream &os, const number &n)
{
return os << n.to_hex_string();
}
|