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. There are also two complex operators that can be used to assign the value directly to the value on left. These are the <<= operator
and the >>= operator
.
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.
Demo Code:
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; // Gives output 8
// Right shifting a by 2 will make it 00000010, ie, 2
a = a >> 2;
cout << a << endl; // Gives output 2
return 0;
}
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.
solved Need an explanation on a shift syntax in code – C++ [closed]