I'm currently doing a college task where I have to add two binary numbers in C (without arrays). I understand the algorithm, I mean, how to add binary numbers, but I don't get how to write it as code. In this specific exercise the user has to enter two digits (0 or 1) per Operand. a1 and a2 for the first Operand and b1 and b2 for the second one. For example:
User introduce 1 1 (a1, a2) for the first binary number and 0 1 (b1, b2) for the second. The result (100) is what the programm have to return back. I have already seen some code examples, but still don't understand how it works. Using if and else if statements I can understand a part of it (if I'm not wrong):
if((a2 == 0) && (b2 == 0)) {
sum = 0;
carry = 0;
}
else if((a2 == 0) && (b2 == 1) || (a2 == 1) && (b2 == 0)) {
sum = 1;
carry = 0;
}
else if((a2 == 1) && (b2 == 1)) {
sum = 0;
carry = 1;
{
But how do I continue? I want to make clear that I don't want the code (I can copy it from Internet if I want to), I want to understand it.
andisn't a keyword in C). You just need to account for more digits and forward the carry out from the previous digit.a,b, andcarry_in. There are two outputs,candcarry_out. For each digit, thecarry_invalue is equal tocarry_outfor the previous addition, with the initialcarry_in = 0. There you have it, the building blocks for a Full Adder. For example, if you are adding 01 and 01, you havea1=1,b1=1,carry_in=0. Result:c1=0andcarry_out=1. For the next digit you thus havea2=0,b2=0,carry_in=1.