How to add binary numbers in C?

Viewed 447

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.

1 Answers

The comments hint this already but I think this deserves a whole answer on how to do this (merge between logic circuit and code without LUTs) so here it is:

Truth table of (cy c) = a+b+cy':

a b cy'| cy c
-------|-----
0 0 0  |  0 0 
0 0 1  |  0 1
0 1 0  |  0 1
0 1 1  |  1 0
1 0 0  |  0 1 
1 0 1  |  1 0 
1 1 0  |  1 0
1 1 1  |  1 1

Karnaugh maps

[c]     bbb  | [cy]    bbb
      aaa    |       aaa  
    0 1 0 1  |     0 0 1 0
cy' 1 0 1 0  | cy' 0 1 1 1

Logic equations:

c  = a^b^cy'              // btw this is also how even/odd parity is computed
cy = (cy'&(a|b))|(a&b)

Some example code:

void add(int &cy,int &c,int a,int b,int _cy)    // (cy c) = a+b+_cy
    {
    cy=((a|b)&_cy)|(a&b);
    c =a^b^_cy;
    }

...

int a1,a2,b1,b2,c1,c2,cy;   // assuming a2,b2,c2 is lsb that is weird usually lowest index is lsb

// obtain a1,a2,b1,b2
cy=0;                       // cy at start is zero
add(cy,c2,a2,b2,cy);        // lsb bit
add(cy,c1,a1,b1,cy);        // next bit ...
// print cy,c1,c2 as result

...

I do not code in C but C++ instead so I hope did not use something that is restricted in C. So I just packed the 1bit adder into a function and call it for each bit from lsb to msb ... If also functions are not allowed then you need to copy the function code for each bit and rewrite the variables indexes ...

Beware the allowed values for a?,b?,c?,cy are only { 0 , 1 } as I used bitwise operators !!!

Also I did not optimize the equations ... you might want to use De Morgan Laws and or logic identities to improve/simplify/normalize them ...

As you can see you can do logic equations directly using logic operators no need for slow if/else statements

Related