我试图将我的任意精度整数类转换为能够使用不只是每个数字 8 位的数字。我偶然发现了一个奇怪的问题:我可以使用uint16_t
我的基本数字类型,但不能使用uint32_t
. 我的代码将返回错误的结果。我用来找出问题所在的示例是0x1111111111111111 * 0x1111111111111111
,应该是0x123456789abcdf00fedcba987654321
。但是,我得到了0x123456789abcdf0fedcba987654321
。
我认为我已经更改了所有硬编码类型,因此更改基本数字类型无关紧要,但显然不是。
以下是相关代码:
typedef uint32_t digit; // original code uses uint8_t; uint16_t works too
typedef uint64_t double_digit; // int type to hold overflow values
typedef std::deque <digit> base;
const digit NEG1 = -1; // uint8_t -> 255, uint32_t -> 4294967295
const digit BITS = sizeof(digit) << 3; // sizeof gives the number of bytes, so multiply that by 8 to get the number of bits
const digit HIGH_BIT = 1 << (BITS - 1); // uint8_t -> 128
// left bit shift. sign is maintained
integer operator<<(uint64_t shift){
if (!*this || !shift)
return *this;
base out = digits;
for(uint64_t i = 0; i < (shift / BITS); i++)
out.push_back(0);
shift %= BITS;
if (shift){
out.push_back(0);
return integer(out, _sign) >> (BITS - shift);
}
return integer(out, _sign);
}
// right bit shift. sign is maintained
integer operator>>(uint64_t shift){
if (shift >= bits())
return integer(0);
base out = digits;
for(uint64_t i = 0; i < (shift / BITS); i++)
out.pop_back();
shift %= BITS;
if (shift){
base v;
for(d_size i = out.size() - 1; i != 0; i--)
v.push_front(((out[i] >> shift) | (out[i - 1] << (BITS - shift))) & NEG1);
v.push_front(out[0] >> shift);
out = v;
}
return integer(out, _sign);
}
// operator+ calls this
integer add(integer & lhs, integer & rhs){
base out;
base::reverse_iterator i = lhs.digits.rbegin(), j = rhs.digits.rbegin();
bool carry = false;
double_digit sum;
for(; ((i != lhs.digits.rend()) && (j != rhs.digits.rend())); i++, j++){
sum = *i + *j + carry;
out.push_front(sum);
carry = (sum > NEG1);
}
for(; i != lhs.digits.rend(); i++){
sum = *i + carry;
out.push_front(sum);
carry = (sum > NEG1);
}
for(; j != rhs.digits.rend(); j++){
sum = *j + carry;
out.push_front(sum);
carry = (sum > NEG1);
}
if (carry)
out.push_front(1);
return integer(out);
}
// operator* calls this
// Long multiplication
integer long_mult(integer & lhs, integer & rhs){
unsigned int zeros = 0;
integer row, out = 0;
for(base::reverse_iterator i = lhs.digits.rbegin(); i != lhs.digits.rend(); i++){
row.digits = base(zeros++, 0); // zeros on the right hand side
digit carry = 0;
for(base::reverse_iterator j = rhs.digits.rbegin(); j != rhs.digits.rend(); j++){
double_digit prod = (double_digit(*i) * double_digit(*j)) + carry;// multiply through
row.digits.push_front(prod & NEG1);
carry = prod >> BITS;
}
if (carry)
row.digits.push_front(carry);
out = add(out, row);
}
return out;
}
是否有一些明显的我错过了可能导致错误计算的东西?我一口气盯着这段代码看了太久。
完整的修改代码在这里。
编辑:我已经在ideone上测试了代码,它返回了这个计算的正确值,但我的电脑仍然没有。对此有什么好的解释吗?