在C ++中有点添加

时间:2018-03-22 06:34:40

标签: c++ bit-manipulation

我希望在以下链接中使用以下代码

https://www.geeksforgeeks.org/divide-and-conquer-set-2-karatsuba-algorithm-for-fast-multiplication/

// The main function that adds two bit sequences and returns the addition
string addBitStrings( string first, string second )
{
    string result;  // To store the sum bits

    // make the lengths same before adding
    int length = makeEqualLength(first, second);
    int carry = 0;  // Initialize carry

    // Add all bits one by one
    for (int i = length-1 ; i >= 0 ; i--)
    {
        int firstBit = first.at(i) - '0';
        int secondBit = second.at(i) - '0';

        // boolean expression for sum of 3 bits
        int sum = (firstBit ^ secondBit ^ carry)+'0';

        result = (char)sum + result;

        // boolean expression for 3-bit addition
        carry = (firstBit&secondBit) | (secondBit&carry) | (firstBit&carry);
    }

    // if overflow, then add a leading 1
    if (carry)  result = '1' + result;

    return result;
}

我很难理解以下表达式

// boolean expression for sum of 3 bits
int sum = (firstBit ^ secondBit ^ carry)+'0';

和其他表达

// boolean expression for 3-bit addition
carry = (firstBit&secondBit) | (secondBit&carry) | (firstBit&carry);

两者有什么区别?他们想要实现什么目标?

由于

1 个答案:

答案 0 :(得分:1)

要理解这一点,包含所有可能组合的表可能会有所帮助。 (为了我们的运气,组合的数量非常有限。)

以AND(&),OR(|),XOR(^)开头:

 a | b | a & b | a | b | a ^ b
---+---+-------+-------+-------
 0 | 0 |   0   |   0   |   0
 0 | 1 |   0   |   1   |   1
 1 | 0 |   0   |   1   |   1
 1 | 1 |   1   |   1   |   0

把它放在一起:

 a | b | carry | a + b + carry | a ^ b ^ carry | a & b | b & carry | a & carry | a & b | a & carry | b & carry
---+---+-------+---------------+---------------+-------+-----------+-----------+-------------------------------
 0 | 0 |   0   |      00       |      0        |   0   |    0      |     0     |             0
 0 | 0 |   1   |      01       |      1        |   0   |    0      |     0     |             0
 0 | 1 |   0   |      01       |      1        |   0   |    0      |     0     |             0
 0 | 1 |   1   |      10       |      0        |   0   |    1      |     0     |             1
 1 | 0 |   0   |      01       |      1        |   0   |    0      |     0     |             0
 1 | 0 |   1   |      10       |      0        |   0   |    0      |     1     |             1
 1 | 1 |   0   |      10       |      0        |   1   |    0      |     0     |             1
 1 | 1 |   1   |      11       |      1        |   1   |    1      |     1     |             1

请注意,a + b的最后一位数字与a ^ b ^ carry以及a & b | a & carry | b & carry的结果完全类似,与a + b的第一位数字相似。

最后一个细节是,将'0'(数字0的ASCII码)添加到resp。 result(0或1)再次将其转换为相应的ASCII字符('0''1')。