# Addition of two binary numbers using C

**Basic Theory**

Addition of binary numbers is far simpler than that of a decimal number. This is because binary addition includes addition between 1 and 0 only. The addition process results into two units: sum and carry

sum = a xor b xor c carry = ab + bc+ ac

Initially, the carry bit is set to be 0. This process is continued until all the bits in a binary number finish.

**Code Assumption**

The following code uses 8 – bit binary unsigned integer. This means each integer can hold from 0 to 255 in decimal. So user can add up to 255. If the result is greater than 255, then the condition of overflow occurs. The code contains the following segments

- Decimal to Binary Conversion
- Addition of two binary numbers

This is, the first user enters the operands in decimal format like 100 and 125. Then program converts both operands into an equivalent binary format like 011001000 and 01111101. The program adds two binary numbers using the above method. The results are obtained in binary format like 11100001. Then finally the binary number is converted back to decimal format like 225.

**Source Code:**

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 | #include <stdio.h> #include <math.h> void decimalToBinary(int op1, int aOp[]){ int result, i = 0; do{ result = op1 % 2; op1 /= 2; aOp[i] = result; i++; }while(op1 > 0); } int binaryToDecimal(int array[]){ int sum = 0, i; for(i = 0; i < 8; i++){ if(array[i]) sum += pow(2,i); } return sum; } void showBinary(int array[], int n){ int i; for(i = n -1; i >=0; i--){ printf("%d ", array[i]); } printf("\n"); } int addBinary(int a1[], int a2[], int result[]){ int i, c = 0; for(i = 0; i < 8 ; i++){ result[i] = ((a1[i] ^ a2[i]) ^ c); //a xor b xor c c = ((a1[i] & a2[i]) | (a1[i] &c)) | (a2[i] & c); //ab+bc+ca } result[i] = c; return c; } int main(){ int op1, op2, sum; int aOp1[8] = {0,0,0,0,0,0,0,0}; int aOp2[8] = {0,0,0,0,0,0,0,0}; int aSum[8] = {0,0,0,0,0,0,0,0}; printf("Enter two operands (0 to 255): "); scanf("%d %d", &op1, &op2); while(op1 < 0 || op1 > 255 || op2 < 0 || op2 > 255 ){ printf("Enter two operands (0 to 255): "); scanf("%d %d", &op1, &op2); } decimalToBinary(op1, aOp1); decimalToBinary(op2, aOp2); printf("Binary Equivalent of %d is ",op1); showBinary(aOp1, 8); printf("Binary Equivalent of %d is ",op2); showBinary(aOp2, 8); if(!addBinary(aOp1, aOp2, aSum)){ printf("Sum of the two number is : "); showBinary(aSum, 8); sum = binaryToDecimal(aSum); printf("Decimal eqivalent is: %d", sum); }else{ printf("Overflow"); } return 0; } |

## Recent Comments