Bitshift operators in C

Bitshift operators are used to move the bits of a variable in a perticular direction.

Right Shift Operator (>>)

The right shift operator (>>) shifts each bit inside a variable a certain number of places to the right. The number of places shifted depends on the value given to the right of the operator.

Syntax:   k = i >> j;
where   k => resultant
             i => variables whose bits are being shifted
             j => value indicating how many places the bits need to be shifted

When the resultant value has to be stored in the variable being operated on, the syntax may be abbreviated to the following:
i >>= j;
Expanded form: [i = i >> j]

Example: The statement i >> 5 would shift all the bits of i five places to the right.

To understand what exactly happens to the bits in the variable, let us take a character variable ch which stores the value 'j' with ASCII value 106.
The binary equivalent of 106 is 01101010 which is stored in 'ch'.
Now, ch >> 2 would shift all bits to the right by two places giving the result 00011010.

It may be noted from the above example that as the bits are shifted vacant places created by the shifting operations are filled up by zeros.

Left Shift Operator (<<)

The left shift operator (<<) shifts each bit inside a variable a certain number of places to the left. The number of places shifted depends on the value given to the right of the operator.

Syntax:   k = i << j;
where   k => resultant
             i => variables whose bits are being shifted
             j => value indicating how many places the bits need to be shifted

When the resultant value has to be stored in the variable being operated on, the syntax may be abbreviated to the following:
i <<= j;
Expanded form: [i = i << j]

Example: The statement i << 5 would shift all the bits of 'i' five places to the left.

To understand what exactly happens to the bits in the variable, let us take a character variable 'ch' which stores the value 'j' with ASCII value 106.
The binary equivalent of 106 is 01101010 which is stored in 'ch'.
Now, ch << 2 would shift all bits to the left by two places giving the result 01101000.

It may be noted from the above example that as the bits are shifted vacant places created by the shifting operations are filled up by zeros.

About our authors: Team EQA

You have viewed 1 page out of 252. Your C learning is 0.00% complete. Login to check your learning progress.

#