Addition of two binary numbers using C

Basic Theory

Loading…
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
  • Binary to Decimal conversion
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:
#include 
#include 
 
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 =0; i--){
        printf("%d ", array[i]);
 
    }
    printf("\n");
 }
 
 
 
int addBinary(int a1[], int a2[], int result[]){
    int i, c = 0;
    for(i = 0; i  255 || 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;
 }
Loading…