C - Shifting binary values

Introduction

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.

Demo

#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: "); 
    scanf("%d",&bshift); 

    for(x=0;x<8;x++) 
    { 
        printf("%s\n",to_binary(bshift)); 
        bshift = bshift << 1; 
    } 

    return(0); 
} 
char *to_binary(int n) 
{ 
   static char bin[9]; 
   int x; 

   for(x=0;x<8;x++) 
   { 
       bin[x] = n & 0x80 ? '1' : '0'; 
       n <<= 1; 
   } 
   bin[x] = '\0'; 
   return(bin); 
}

Result

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