What are shift operators in C++?

C++Server Side ProgrammingProgramming

The bitwise shift operators are the right-shift operator (>>), which moves the bits of shift_expression to the right, and the left-shift operator (<<), which moves the bits of shift_expression to the left.

The left-shift operator causes the bits in shift-expression to be shifted to the left by the number of positions specified by additive-expression. The bit positions that have been vacated by the shift operation are zero-filled. A left shift is a logical shift (the bits that are shifted off the end are discarded, including the sign bit).

The right-shift operator causes the bit pattern in shift-expression to be shifted to the right by the number of positions specified by additive-expression. For unsigned numbers, the bit positions that have been vacated by the shift operation are zero-filled. For signed numbers, the sign bit is used to fill the vacated bit positions. In other words, if the number is positive, 0 is used, and if the number is negative, 1 is used.

example

#include<iostream>
using namespace std;
int main() {
   int a = 1, b = 3;
   
   // a right now is 00000001
   // Left shifting it by 3 will make it 00001000, ie, 8
   a = a << 3;
   cout << a << endl;
   
   // Right shifting a by 2 will make it 00000010, ie, 2
   a = a >> 2;
   cout << a << endl;
   return 0;
}

Output

This will give the output −

8
2

Note that these operators behave very differently with negative numbers. The result of a right-shift of a signed negative number is implementation-dependent. If you left-shift a signed number so that the sign bit is affected, the result is undefined.

There are also 2 complex operators that can be used to assign the value directly to the value on left. These are the <<= operator and the >>= operator.

Refer to https://msdn.microsoft.com/en-us/library/336xbhcz.aspx for a much detailed inspection of the shift operators.

raja
Published on 16-Feb-2018 10:24:06
Advertisements