C - Shifting binary values


The << and >> operators shift bits in value, marching them to the left or right, respectively.

Here's the format for the << operator:

v = int << count; 

int is an integer value.

count is the number of places to shift the value's bits to the left.

The result of this operation is stored in variable v.

Any bits that are shifted to the left beyond the width of the int variable x are lost.

New bits shifted in from the right are always 0.


#include <stdio.h> 

char *to_binary(int n); 

int main() //from w w w  .  j  a  v a 2 s .  c  o  m
    int bshift,x; 

    printf("Type a value from 0 to 255: "); 

        bshift = bshift << 1; 

char *to_binary(int n) 
   static char bin[9]; 
   int x; 

       bin[x] = n & 0x80 ? '1' : '0'; 
       n <<= 1; 
   bin[x] = '\0'; 


The net effect of a left bit shift is to double a value.

That holds true to a certain point: Obviously, the farther left you shift, some bits get lost and the value ceases to double.

This trick works only for unsigned values.

Related Topic