Left Shift and Right Shift Operators
Learn the functionality of the left shift and right shift operators in C.
The left shift operator
The left shift operator is a binary operator that operates on two operands as shown below:
Example
5 << 2
shifts all the bits in 5
two places to the left. The binary of 5
is 00000101
; therefore, upon shifting all the bits two places to the left, the answer would be 00010100
, which in decimal is 20
.
📝 Note: When the bits are shifted to the left, blanks will be created on the right. These blanks will be filled by
0's
.
Program
See the code given below!
C
#include<stdio.h>int main() {// Initialize variableunsigned char ch = 33 ;// Display numberprintf( "%d ", ch ) ;// Display number in decimal format after left-shiftingprintf( "%d ", ch << 1) ;// Display number in hex format after left-shiftingprintf( "%#x ", ch << 1) ;}
Line 9: ch << 1
eliminates one bit from the left-hand side of the binary stored in ch
and shifts balance bits one position to the left. Left shifting an operand1 << operand2
is equivalent to multiplying operand1 by 2operand2.
...