Decimal to Binary Conversion - Bitwise Right shift Operator

It is a number system conversion from decimal value into binary bits is carried out using 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 (most 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=10 , move 1 bit using right-shift
                    
                        binary 8-bits  x  = 00001010 
                                       x = x >> 1   move 1 bit 
                       (remove one bit from LSB (0) and  add one bit (0) into MSB 
   
                        binary 8-bits  x  = 00000101                                                
  
                        and x's decimal value becomes 5.                        
  

Decimal to binary conversion using Bitwise Right-shift Operator - algorithm

Declaration
Input Read integer decval
Output char bits[9]
Temp var integer n=0
   
Loop decval not equal zero
  bits[n] = decval AND 1 then '1' else '0'
  decval right shift by 1
  n=n+1
End Loop
Output print,bits

Decimal into Binary using Right shift operator - Java code

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

 

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

int main() {


   int decval;
   char bits[9]; int n=0;
   
   printf ("\n Bitwise Right shift Operator Binary Conversion");
   
   printf("\n Enter a Decimal value" );
   scanf("%d", &decval);
   
   while ( decval !=0 ) {   
       bits[n]=( decval & 1 ) ==1 ? '1' :'0';
       decval = decval >>1;    
    n++;
   }
   bits[n] ='\0';
   

   printf( "Binary bits :%s",strrev(bits));
   return 0;
}

 

Decimal into Binary using Right shift operator - C program Output


  Bitwise Right-shift Operator Binary Conversion

     Enter a Decimal value : 10

     Binary bits : 1010





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