Question

I'm trying to calculate the sum of 2 bits using basic binary arithmetic and currently, I'm doing this:

function Add(bool a, bool b, bool carry)
{
    return
    {
         Result: a ^ b ^ carry,
         Carry: a & b | a & carry | b & carry
    };
}

Is there a way to shorten the expression that calculates the Carry or I have to manually check all possible combinations?

Était-ce utile?

La solution

There is only a minor simplification:

a & b | (a | b) & carry

This is equivalent to

a & carry | (a | carry) & b

and

carry & b | (carry | b) & a

Autres conseils

If you're counting by operations, and you're willing to count ?: as one operation, then you can improve on this answer with:

carry ? (a|b) : (a&b)

That is five operands and three operations. Or maybe 3.5 operations. But it's still better than the other answer with 4 operations.

If you're focused on the idea that the function is 'any two or more of the three', this I like this form because it says "If one is high, either of the other two, otherwise both of the other two."

If I'm not mistaken, you can add bools in C. You could add the three bools together and then check if the value is greater than 1. I doubt this would be a good idea from a performance perspective. It might be worth considering if you had more than three boolean values and wanted to check if a certain number are set.

I realize this makes no sense for what you want to do specifically but it is a solution for the more general problem of given X bools check if Y (or at least Y) are set.

Pseudo code for a generic full adder (what you are describing). Most languages will support this pseudo code.

Using a temporary field means that this will take five operations, two EXCLUSIVE OR, two AND, and one OR.

Inputs: a, b, Cin
Outputs: sum, Cout

temp = a XOR b
sum = temp XOR Cin
Cout = (a AND B) OR (temp AND Cin)

You can cast the booleans to integers and directly compute the result.

int sum= (int)a + (int)b + (int)carry;
Result: (bool)(sum & 1);
Carry:  (bool)(sum >> 1);
Licencié sous: CC-BY-SA avec attribution
scroll top