Q:

C program to find Binary Addition and Binary Subtraction

0

C program to find Binary Addition and Binary Subtraction

Binary addition/subtraction is similar to regular (daily life) addition/subtraction, but here addition/subtraction performs only two digits those are 0 and 1, these are binary digits hence such kind of addition/subtraction is called binary addition/subtraction.

Example of Binary Addition:
Take two numbers, suppose numbers are 10 and 20 their binaries are 1010 and 10100.

In binary addition 
0+0	=	0
0+1	=	1
1+0	=	1
1+1	=	0	(1 carries out)
Now add 10 and 20
10	=	0 1 0 1 0
20	=	1 0 1 0 0
=	1 1 1 1 0
=	30

Example of Binary Subtraction:

Take two numbers, suppose numbers are 20 and 10 their binaries 10100 and 1010.

In binary subtraction 
0-0	=	0
1-0	=	1
0-1	=	1	(1 borrows out)
1-1	=	0

Now sub 10 from 20
20	=	1 0 1 0 0
10	=	0 1 0 1 0
=	0 1 0 1 0
=	10

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Consider the example:

#include <stdio.h>

// function for Binary Addition
int binAddition(int a, int b)
{
    int c; //carry
    while (b != 0) {
        //find carry and shift it left
        c = (a & b) << 1;
        //find the sum
        a = a ^ b;
        b = c;
    }
    return a;
}

// function for Binary Subtraction
int binSubtracton(int a, int b)
{
    int carry;
    //get 2's compliment of b and add in a
    b = binAddition(~b, 1);

    while (b != 0) {
        //find carry and shift it left
        carry = (a & b) << 1;
        //find the sum
        a = a ^ b;
        b = carry;
    }
    return a;
}

int main()
{
    int number1, number2, binAdd, binSub;

    printf("Input first integer value: ");
    scanf("%d", &number1);

    printf("Input second integer value: ");
    scanf("%d", &number2);

    binAdd = binAddition(number1, number2);
    binSub = binSubtracton(number1, number2);

    printf("Binary Addition: %d\n", binAdd);
    printf("Binary Subtraction: %d\n", binSub);

    return 0;
}

Output:

    Input first integer value: 30
    Input second integer value: 5
    Binary Addition: 35
    Binary Subtraction: 25

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C language important programs ( Advance Programs )

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C program to print character without using format ... >>
<< Program to print weekday of given date...