我有这个功能,一切都有效,直到a和b都等于1.当发生这种情况时,当它应该只有0或1时,进位位将变为2.我的算法对于进位位是错误的 carry_bits | =((a& mask)&(b& mask))<< 1U;
bool add7bits( unsigned int a, unsigned int b, unsigned int *carry_out, unsigned int *overflow_out, unsigned int *sum_out)
{
if ( a > ( ( 1u << NUM_BITS ) - 1 ) )
{
cout << "a value: " << a << " is too large" << endl;
return false;
}
else if ( b > ( ( 1u << NUM_BITS ) - 1 ) )
{
cout << "b value: " << b << " is too large" << endl;
return false;
}
else
{
unsigned int sum_bits = 0;
unsigned int carry_bits = 0;
// Use a mask to access the specific bits of interest
unsigned int mask = 1u;
// Handle rightmost bit as a half-adder (no carry input)
// sum = a ^ b
// c_out = a & b
sum_bits |= ( a & mask) ^ ( b & mask);
// The carry _out_ from this stage sets the carry in for the next,
// that is, the next higher bit in the carry_bits value
carry_bits |= ((a & mask) & (b & mask)) << 1u;
// The remaining bits must be handled with the full adder logic. The last
// adder in the chain's carry out becomes the carry output return
// value of this function.
mask = 1u << 1;
sum_bits |= ((a & mask) ^ (b & mask) ^ carry_bits);
carry_bits |= ((a & mask) & (b & mask)) << 1u;
mask = 1u << 2;
sum_bits |= ((a & mask) ^ (b & mask) ^ carry_bits);
carry_bits |= ((a & mask) & (b & mask)) << 1u;
mask = 1u << 3;
sum_bits |= ((a & mask) ^ (b & mask) ^ carry_bits);
carry_bits |= ((a & mask) & (b & mask)) << 1u;
mask = 1u << 4;
sum_bits |= ((a & mask) ^ (b & mask) ^ carry_bits);
carry_bits |= ((a & mask) & (b & mask)) << 1u;
mask = 1u << 5;
sum_bits |= ((a & mask) ^ (b & mask) ^ carry_bits);
carry_bits |= ((a & mask) & (b & mask)) << 1u;
// Handle bit 6 separately.
mask = 1u << 6;
sum_bits = ((a ^b) ^ carry_bits);
carry_bits |= ((a & mask) & (b & mask)) << 1u;
// Determine the overflow by checking if a and b are both 1.
bool overflow = false;
if ((a & mask) & (b & mask))
overflow = true;
// ...
//
*sum_out = sum_bits;
*carry_out = carry_bits;
*overflow_out = overflow;
cout << a << " + " << b << " = " << *sum_out << endl;;
cout << "Carry: " << *carry_out << endl;
cout << "Overflow: " << *overflow_out << endl;
return true;
}
}
答案 0 :(得分:1)
进位为1,它位于第二位,因此carry_bits
为...0010
或2。
答案 1 :(得分:0)
您将所有先前的进位位置入每级的和位,而不仅仅是当前级的进位位。你想要
sum_bits |= ((a & mask) ^ (b & mask) ^ (carry_bits & mask));
在每个阶段,或等同,更简单:
sum_bits |= (a ^ b ^ carry_bits) & mask;
您的执行计算不正确 - 它不考虑进位。你想要:
carry_bits |= ((a & b | a & carry_bits | b & carry_bits) & mask) << 1;
您的最终执行位是进位位的第8位,因此您需要:
*carry_out = carry_bits >> NUM_BITS;
只写那一点。
“溢出”在这里没有多大意义,因为你似乎在进行无符号加法(因此“溢出”到它存在的程度,与执行相同)。如果你正在进行2s-complement signed add,你需要最后两个进位的xor:
*overflow_out = ((carry_out >> NUM_BITS) ^ (carry_out >> (NUM_BITS-1))) & 1;