Binary to Decimal Conversion - Bitwise Right shift Operator

It is number system conversion from binary (base -2) to decimal (base -10) is carried out by bitwise >> (right-shift) operator.

The Right shift operator moves the bit position of a integer towards right direction. it removes bits from LSB (least significant bit) and add bits (0s) into MSB (least significant bit) and the number bits to remove and to add depends on a operand value next to the right shift operator.

      For example,  the integer variable x=74 , move 2 bit using right-shift operator
                    
                    binary 8-bits of x  = 01001010 
                                     x = x >> 2   move 2 bit 
               (remove two bits from LSB (10) and add two bits (00) into MSB 
   
                2-bits shifted binary 8-bits of x  = 00010010                                                
                and x's decimal value becomes 18.                        
  

Binary to decimal conversion using Bitwise Right-shift Operator - algorithm

Declaration
Input Read char bits[9]
Output set integer decval=0
Temp var integer n,len=0
  
  len = strlen(bits)
Loop n=len-1 to 0
  decval right shift by 1
  bits[n] == '1' then decval OR by 128
  n=n-1
End Loop
Output print,bits

Binary into Decimal using Right shift Operator - c program

The C program converts binary bits into decimal value using bitwise << (right-shift) operator. It has given binary bits as inputs and returns a decimal value as output.

 

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

int main() {


   int decval;
   char bits[9]; int n=0;
   
   printf ("\n Bitwise Right shift Operator decimal Conversion");
   
   printf("\n Enter a binary bits: " );
   scanf("%s", &bits);
   
   int len = strlen(bits);
   
   decval=0;
   for( n=len-1; n>=0 ; n-- ) {     
  decval = decval >>1;   
  if ( bits[n] =='1' )
      decval = decval | 128;            
   }   
      
   printf( "\nBinary bits :%s",bits);
   printf("\nDecimal value :%d ",decval);
   return 0;
}

 

Binary into decimal conversion - Output


  Bitwise Right-shift Operator Decimal Conversion

     Enter a binary bits : : 1111

     Decimal value : 15    





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