Friday, 10 May 2013

C program for binary subtraction using two's complement


1 Pseudocode:

1.      Start
2.      Ask user to enter two 8-bit numbers: num1, num2
3.      Begin Subtraction from LSB
4.      diff = num1[i] – num2[i]
5.      If difference of two bits < 0, num1[i-1] = num1[i-1] - 1
6.      diff = absolute(diff % 2)
7.      Repeat 5 through 7 until all bits are added
8.      Display diff
9.      End

2 Program:
#include <stdio.h>
#include <conio.h>
#include <math.h>

void main(){
            clrscr();
            int numa[8]={0},numb[8]={0},diff[8]={0};
            printf("\tSUBTRACTION USING TWO'S COMPLEMENT");
            printf("\nEnter two 8-bit binary numbers\n");

            printf("\nEnter first number: ");
            for(int i = 0; i<8; i++){
                        scanf("%d",&numa[i]);
            }
            printf("\nEnter second number: ");
            for(i = 0; i<8; i++){
                        scanf("%d",&numb[i]);
            }

            for(i = 7; i >= 0; i--){
                        diff[i] = numa[i] - numb[i];
                        if(diff[i] < 0){
                                    numa[i-1] = numa[i-1] - 1;
                        }
                        diff[i] = fabs(diff[i]%2);
            }
            printf("\nDifference is: ");
            for(i = 0; i<8; i++){
                        printf("%d",diff[i]);
            }

            getch();
}

©Dixit Bhatta 2013

No comments:

Post a Comment

Was this post helpful? Ask any questions you have, I will try to answer them for you.

Follow by Email