Monday, 27 July 2015

C program to find the 2's complement of a binary number


The word competent means opposite. That is if there is one in the number then it's competent is zero. In Binary number systems complements are used to perform various arithmetic operations like addition, subtraction, multiplication ext...


How to  find the 2's complement of a binary number:


  For example consider the number  11111 is binary number. The 2's complement of a number can be obtained as follows.

  •            The given binary number is 11111
  •            The 1's complement of given number is 00000
  •            Then add 1 to the 1's complement number that is 00000+1 = 00001
 There four the 2's complement of 11111 is 00001


Here is the  C Program to find the 2's complement of a binary number


 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
#include <stdio.h>
#include<conio.h>

void complement (char *a);
void main()
{
 char a[16];
 int i;
 clrscr();
 printf(" Welcome to www.tutorialtpoint.net\n");
 printf("Enter the binary number\n");
 gets(a);
 for(i=0;a[i]!='\0'; i++)
 {
  if (a[i]!='0' && a[i]!='1')
  {
   printf("The number entered is not a binary number. Enter the correct number");
   exit(0);
  }
 }
complement(a);
getch();
}
void complement (char *a)
{
 int l, i, c=0;
 char b[16];
 l=strlen(a);
 for (i=l-1; i>=0; i--)
 {
  if (a[i]=='0')
  b[i]='1';
  else
  b[i]='0';
 }
 for(i=l-1; i>=0; i--)
 {
 if(i==l-1)
 {
  if (b[i]=='0')
  b[i]='1';
  else
  {
   b[i]='0';
   c=1;
  }
 }
 else
 {
  if(c==1 && b[i]=='0')
  {
   b[i]='1';
   c=0;
  }
 else if (c==1 && b[i]=='1')
 {
  b[i]='0';
  c=1;
 }
}
}
b[l]='\0';
printf("The 2's complement is %s", b);
}

After successful execution of the above program it generates the following output


0 comments:

Post a Comment

Scribe to Youtube Channel

Advertisement

Find Us On Facebook

C Programming

More

C++ Tutorial

More

Java Tutorial

More

software engineering

More

MS Office

More

Database Management

More
Top