Join Regular Classroom : Visit ClassroomTech

Shift operator in C

Shift operator:

There are two types of shift operator in C programming language. 

  1. Left shift operator
  2. Right shift operator

1. Left shift (<<) : The Left Shift (<<) operator is called as the arithmetic left shift operator. This operator works for both signed as well as unsigned numbers and also to types like int, long, char, etc.
This operator shifts the left operand, left by the number of bits specified by the right operand. For example –

Explanation : Here we are operating the left shift operation on the number 12. The bitwise representation(assuming that it’s a 8 bit number) of the number 12 is – 0000 1100. The expression “int b = a<<b”, means ‘a’ will be left shifted by ‘b’, that is 2(here). Therefore after performing the left shift operation the bitwise representation of the number will be 0011 0000, that is 48. Therefore we are getting a = 12 & b = 48.

2. Right shift (>>) : This works same as the left shift operator, but this operator shifts the left operand, right by the number of bits specified by the right operand. For example-

Explanation : Here we are operating the right shift operation on the number 12. The bitwise representation(assuming that it’s a 8 bit number) of the number 12 is – 0000 1100. The expression “int b = a>>b”, means ‘a’ will be right shifted by ‘b’, that is 2(here). Therefore after performing the right shift operation the bitwise representation of the number will be 0000 0011, that is 3. Therefore we are getting a = 12 & b = 3.

Categories
Pages
Recent Posts