そのため、私が取り組んでいるプロジェクト オイラー問題のリンク リストを使用して、Unlimited Unsigned 整数クラス全体を実装しました。すべての論理ビット操作が正しいことを確認しました (見たい場合は投稿できますが)。私はすでにすべての演算子と操作を実装しています。ただし、減算 (およびそれを使用するすべてのもの、つまり除算と剰余) は機能しません。次のテストを実行すると、次のようになります。
LimitlessUnsigned limitless = 0x88888888u;
limitless = limitless << 4;
LimitlessUnsigned tester = 0x88888884u;
tester = tester << 4;
//limitless = limitless >> 5;
LimitlessUnsigned another = limitless - tester;
デバッガーから次の値を取得します。
another LimitlessUnsigned
integerList std::__1::list<unsigned int, std::__1::allocator<unsigned int> >
[0] unsigned int 0b11111111111111111111111111111111
[1] unsigned int 0b00000000000000000000000001000000
limitless LimitlessUnsigned
integerList std::__1::list<unsigned int, std::__1::allocator<unsigned int> >
[0] unsigned int 0b00000000000000000000000000001000
[1] unsigned int 0b10001000100010001000100010000000
tester LimitlessUnsigned
integerList std::__1::list<unsigned int, std::__1::allocator<unsigned int> >
[0] unsigned int 0b00000000000000000000000000001000
[1] unsigned int 0b10001000100010001000100001000000
引き算の定義と2の褒め言葉で何かを見落としていたようです。余分な 32 ビットを追加する必要があるまで、コードは機能します。最初の 32 から次の 32 までのオーバーフローを説明しています。明らかに、私はこれを正しく行っていません。以下は関連するソースコードです。
void LimitlessUnsigned::Sub(const LimitlessUnsigned& other)
{
if(*this <= other)
{
*this = 0u;
return;
}
LimitlessUnsigned temp = other;
while(temp.integerList.size() > integerList.size())
integerList.push_front(0u);
while(integerList.size() > temp.integerList.size())
temp.integerList.push_front(0u);
temp.TwosComp();
Add(temp, true);
}
void LimitlessUnsigned::Add(const LimitlessUnsigned& other, bool allowRegisterLoss)
{
LimitlessUnsigned carry = *this & other;
LimitlessUnsigned result = *this ^ other;
while(carry != 0u)
{
carry.ShiftLeft(1, allowRegisterLoss);
LimitlessUnsigned shiftedcarry = carry;
carry = result & shiftedcarry;
result = result ^ shiftedcarry;
}
*this = result;
}
void LimitlessUnsigned::Not()
{
for(std::list<unsigned>::iterator iter = integerList.begin(); iter != integerList.end(); ++iter)
{
*iter = ~*iter;
}
}
void LimitlessUnsigned::TwosComp()
{
Not();
Add(1u, true);
}
void LimitlessUnsigned::ShiftLeft(unsigned shifts, bool allowRegisterLoss)
{
unsigned carry = 0u;
bool front_carry = false;
while(shifts > 0u)
{
if((integerList.front() & CARRY_INT_HIGH) == CARRY_INT_HIGH)
front_carry = true;
for(std::list<unsigned>::reverse_iterator iter = integerList.rbegin(); iter != integerList.rend(); ++iter)
{
unsigned temp = *iter;
*iter = *iter << 1;
*iter = *iter | carry;
if((temp & CARRY_INT_HIGH) == CARRY_INT_HIGH)
carry = CARRY_INT;
else
carry = 0u;
}
carry = 0u;
if(front_carry && !allowRegisterLoss)
{
front_carry = false;
integerList.push_front(1u);
}
--shifts;
}
}
更新 私は最終的に問題を解決しました。これが私のブログ投稿とソースコードです。
http://memmove.blogspot.com/2013/04/unlimited-unsigned-integer-in-c.html