We know that a number is actually held as a sequence of bits. Each bit represents a power of two which may or may not be present in the number. For example the value 4 is held as "one times two squared" (0100) and the value 12 would mean "one times two cubed plus one times two squared" (1100).
If we want to, we can perform actions on the bit patterns themselves. We have already seen how AND, OR and Exclusive OR can be used to combine the bit patterns of two values. We use the shift operations to move the bits left or right.
i << 1
This means "shift the value in i
one bit to the right". Because the right most bit of the number is the least significant bit this has the effect of halving the value, for example:
5 << 1
- would give the value 2 because the least significant bit would "drop off" the end.
Shifting in the opposite direction would have the effect of doubling a value, since the "weight" given to each bit would now be twice as much.
You can use the shift operators to "walk" a bit from one end of a byte to another. I use them when I am scanning a keypad and have to turn on each row in turn. You can also use them as quick and dirty divide or multiply by two operators. It is much faster to double a value by shifting than it is to use a multiply and dividing by shifts is much more efficient too.
/* Shifting Operators */
void main ( void )
{
/* create integer variable */
int val = 15 ;
val = val << 2 ;
val = val >> 3 ;
}