Sunday, 13 October 2013

2's Complement of a Binary number

2's complement of binary no. is basicaly = 2^n -binary no.
where
n= no of digit before decimal.

Easy way to find out 2's complement of binary no :

=> Move from right to left of binary no. Untill fist 1 found .
=>Now change all no (1 by 0 && 0 by 1) before above first node .

Examples:

binary no =10010010              2's complement=01101110
binary no=0011001                 2's complement=1100111
binary no=10000                     2's complement= 10000
binary no=0001                       2's complement=0001


ALL highlighted  1 first occurence of 1 

   C program :



 /*  
 To find 2s complement of a binary no  
 */  
 #include<stdio.h>  
 #include<string.h>  
 #include<stdlib.h>  
 main()  
 {  
      char bin[16];  
      int i,j,len;  
      printf("\n enter binary no :");  
      gets(bin); // taking input  
      /*...........chaeck input no is binaty or not............*/  
      len=strlen(bin);  
      for(i=0;i<len;i++)  
      {  
           if(bin[i]!='0' && bin[i]!='1')  
           {  
                printf("\n this is not a binary no");  
                exit(0);  
           }  
      }  
      /*..........end of check input............*/  
      /*............operation time.............*/  
      for(i=len-1;i>=0;i--) //to find position of first occurence of 1;  
      {  
           if(bin[i]=='1')  
           {  
                break;  
           }  
      }  
      for(j=i-1;j>=0;j--) // start loop again from j=first occurence of '1' -1;  
      {  
           if(bin[j]=='0') // replace volue o by 1   
           {  
                bin[j]='1';  
           }  
           else  
            bin[j]='0'; //replace 1 by 0  
      }  
      /*.............end of operation.........*/  
      printf("2's complement of given binaty no is :");  
      puts(bin);// to print string  
 }  

OUTPUT :-


No comments:

Post a Comment

THANKS FOR UR GREAT COMMENT

Blogger Widgets