its as beautiful as a painting...its as delightful as a poem...
U Think its Crazy? then its always a pleasure to go the crazier way....
lets give it a try... just follow and u will find something interesting...

Thursday, December 30, 2010

Beautiful Code- converting Binary to Decimal

When writing this program in my first year, i used scanf to input the binary number into an integer, however, i later realised that the int datatype is designed to store decimal numbers and using them to take input of a binary STRING is unjustified because when we write 10011 in decimal the place value increases in powers of 10 while in case of binary numbers the place value increases in powers of two. And even if you take it in integer you will face two problems
first- you will have to write a complex loop to segregate the binary number into bits and then calculate the place value and face value of each bit
Second and more important you will cross the datatype range very soon. Even if you use a 4 byte compiler you will be able to go to maximum 10 bits which in decimal form means 1024.
So, I suggest taking the binary input in a String rather than int. Furthermore, while taking input in a string it shall be checked that each bit input is 1 or 0 but nothing else.
After taking the input in a string we can easily calculate the place-value of each bit as the index position of that bit and subtracting the index of last bit entered(note: for this it is necessary to take the input in reverse order, i.e. the most significant bit should have highest index).
Below is the C code for Binary to Decimal conversion, you can get many different codes for this but i am trying to write optimized and justified lines of code.. 

#include"stdio.h" /*header file for standard input output functions like printf */
#include"math.h"  /*header file for math functions like pow */
#include"conio.h" /*header file for console input output like getch */
#include"stdlib.h" /*header file for exit function */
int main()
{
   char ch,str[20];
    int i,j;
   unsigned int decimal=0;

printf("\n enter the binary no.(not more than 20 bit) :\n");

for(i=20;i>0;i--)
{
   ch=getche();
       if(ch=='1' || ch=='0')
                  str[i]=ch;
  else if(ch==13) /*it means if the enter key is pressed, because enter key gives the character \r with ascii 13*/
     {
        str[i]='\0'; /* in C a string is terminated by null character */
        j=i; /*we need to remember this index where the string is terminating */
        break;
      }
   else
   {
     printf("wrong binary string, program terminating");
      getch();
      exit(1);
   }
}
for(i=20;i>0;i--)
{
if(str[i]=='\0')
   break;
else
{
   decimal=decimal + ((int)str[i]-'0')*pow(2,i-j-1);
}
}

printf("\n decimal value is %d",decimal);
getch();
return 0;
}

I m Waiting for suggestions, criticism and comments...

No comments:

Post a Comment