Binary to Decimal conversion

The binary number consists of 0's and 1's such a number system has only two distinct digits : {0,1} is called base-2 number system and The decimal number consist of 0's to 9's such a number system has 10 distinct digits {0,1,2,3,4,5,6,7,8,9} is called base 10 number system. The binary to decimal conversion is carried out by following manner.

binary to decimal conversion system

Binary to Decimal - Example of Manual Conversion

   example given binary bits=10101
         convert it into decimal value =?


   decimal value      =1x2^4 + 0x2^3 + 1x2^2  + 0x2^1 + 1x2^0

                      =1x16  + 0x8   + 1x4    + 0x2   + 1x1

                      =16    +    0  +     4  + 0     + 1
             
  decimal value      = 21                

Binary to Decimal conversion - algorithm

 
Declaration
Input Read char bits
Output integer decval
Temp var char abit; integer len,n=0
 
len = strlen(bits)
Loop n =0 to len-1
abit= bits[len-n-1]
if abit=='1' , then decal += power(2,n)
End Loop  
Output print,decval

C program code -  Binary to Decimal conversion

The following c code converts given binary numbers into decimal value using power function. 
 


#include "stdio.h"
#include "string.h"

int main() {
  
 int decval=0; 
 int n=0,nbits=8; 
 int len=0,bit=0;
 char bits[nbits+1];
 
 printf ("\n Binary to Decimal Conversion \n");
 scanf("%s",bits);
  
 len=strlen(bits); 
 for( n=0;n<len;n++) 
  {
  
   bit = bits[len-n-1] =='1' ? 1 : 0;   
   if ( bit==1)
     decval+= pow(2,n);             
  }  
  
 printf ("\n binary bits : %s" ,bits);  
 printf ("\n Decimal value : %d ",decval);   
 return 0;
}
 




Download source code

Comments

Popular posts from this blog

Hexadecimal to Binary Conversion

Convert Octal to Binary

Binary to Decimal conversion -Bitwise Left shift Operator