- Related Questions & Answers
- What are Left Shift and Right Shift Operators (>> and <<) in C#?
- Left Shift and Right Shift Operators in C/C++
- Java Shift operators
- Bitwise right shift operators in C#
- C# Bitwise and Bit Shift Operators
- What are the bitwise zero fill right shift zero operators in Java?
- What are the shift operations in C language?
- What are multiplicative operators in C++?
- What are postfix operators in C++?
- What are equality operators in C++?
- What are unary operators in C#?
- What are relational operators in C#?
- What are postfix operators in C#?
- What are assignment operators in C#?
- What are arithmetic operators in C#?

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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.

#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; }

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.

Advertisements