Thursday, February 9, 2012

Addition of two binary numbers using C

Basic Theory
Addition of binary numbers is far simpler than that of decimal number. This is because, binary addition includes addition between 1 and 0 only. The addition process results into two unit: 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 continue 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 condition of overflow occurs. The code contains following segments
  • Decimal to Binary Conversion
  • Addition of two binary numbers
  • Binary to Decimal conversion
This is , first user enters the operands in decimal format like 100 and 125. Then program converts both operands into equivalent binary format like 011001000 and 01111101. The program adds two binary numbers using above method. The results is obtained in binary format like 11100001. Then finally the binary number is converted back to decimal format like 225.
Source Code:

#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;
 }

No comments:

Post a Comment