Basically, what you need to do is define a class that contains some kind of representation for your number, and then a set of math operators that let you do actual calculations with operands of this class, or mixed calculations between standard types and operands of this class.
For your representation, the above suggestion to use some kind of bit-array seems inefficient IMHO. You'll probably get faster code using
std::vector<unsigned int>
.
Here's a quick hack showing what I have in mind - there's a lot missing, but I hope you get the idea:
class CBigInt {
private:
int sign;
std::vector<unsigned int> mantisse;
void expand(std::size_t size) {
if (size > mantisse.size()) {
std::size_t old_size = mantisse.size();
mantisse.resize(size);
for (std::size_t i = old_size; i < size; ++i)
mantisse[i] = 0;
}
}
public:
CBigInt(int i) : mantisse(1) {
mantisse[0] = iabs(i);
sign = (i>0 ? 1 : (i<0 ? -1 : 0));
}
CBigInt(const CBigInt& other) : mantisse(other.mantisse), sign(other.sign) {
}
CBigInt& operator+=(const CBigInt& other) {
CBigInt newValue(0);
std::size_t size(mantisse.size());
if (other.mantisse.size() > size) {
size = other.mantisse.size();
}
if (other.sign == sign)
newValue.expand(size);
unsigned int carry(0);
if (sign == other.sign) {
newValue.sign = sign;
++size;
for (std::size_t i = 0; i < size-1; ++i) {
if (UINT_MAX-mantisse[i] < carry) {
newValue.mantisse[i] = (carry - (UINT_MAX - mantisse)) - 1;
carry = 1;
}
else {
newValue.mantisse[i] = mantisse[i] + carry;
carry = 0;
}
if (UINT_MAX-newValue.mantisse < other.mantisse[i]) {
newValue.mantisse[i] = (other.mantisse[i] - (UINT_MAX - newValue.mantisse[i])) - 1;
++carry;
}
else {
newValue.mantisse[i] += other.mantisse[i];
}
}
if (carry > 0) {
newValue.mantisse[size] = carry;
}
else {
--size;
}
}
else {
}
sign = newValue.sign;
mantisse.resize(size);
for (std::size_t i = 0; i < size; ++i) {
mantisse[i] = newValue.mantisse[i];
}
}
};
CBigInt operator+(const CBigInt& op1, const CBigInt& op2) {
return CBigInt(op1) += op2;
}
As you can see, even a simple operator can be tricky to implement, especially when you deal with digits containing more than just a single bit. And I'm not even sure I covered all cases - I didn't try to compile this, much less test this code.