Search Tutorials

Wednesday, 24 April 2013

C code to find 2's complement

//This program takes a binary string and converts it into the 2's complement. //

#include<stdio.h>
#include<string.h>
#include<conio.h> 

void revert(char *str,char *comp,int l);

int main()
{
  int i,found=0,l,stlen;
  char *str,*comp;

  clrscr();

printf("\nEnter a binary string\n");
gets(str);
stlen=strlen(str);
l=stlen;
l--;
       // printf("\nlength=%d..%c..",l,str[l]);
while(l)
{
if(found)
{
revert(str,comp,l);
break;
}
else
{
if(str[l]=='1')
found=1;
comp[l]=str[l];
printf("%c",str[l]);
l--;
}
}
printf("\ncopmlement is");
puts(comp);

getch();
return(0);
}


void revert(char *str,char *comp,int l)
{
while(l>=0)
{
if(str[l]=='1')
{
    printf("0");
    comp[l--]='0' ;}
else
{
   printf("1");
   comp[l--]='1';}
}
}



1 comment:

  1. This comment has been removed by a blog administrator.

    ReplyDelete

Back to Top