The right shift operator (>>
) is a bitwise operator in C++ that shifts the bits of a value to the right by a specified number of positions. This operation is equivalent to dividing the value by 2 raised to the power of the specified number.
result = value >> numberOfPositions;
int x = 16; // Binary representation: 0001 0000
int result = x >> 2; // Shifting 2 positions to the right
// After the operation, result = 4
// Binary representation: 0000 0100
The left shift operator (<<
) is a bitwise operator in C++ that shifts the bits of a value to the left by a specified number of positions. This operation is equivalent to multiplying the value by 2 raised to the power of the specified number.
result = value << numberOfPositions;
int y = 2; // Binary representation: 0000 0010
int result = y << 3; // Shifting 3 positions to the left
// After the operation, result = 16
// Binary representation: 0001 0000
-
Division by Powers of 2: It can be used as a faster alternative to integer division by powers of 2.
-
Bitwise Operations: It's commonly used in bitwise operations to extract or modify specific bits in a value.
-
Multiplication by Powers of 2: It can be used as a faster alternative to integer multiplication by powers of 2.
-
Bitwise Operations: Similar to the right shift operator, it's used in bitwise operations to set or clear specific bits.
- When shifting bits to the right, the leftmost bits are filled with the sign bit (0 for positive numbers, 1 for negative numbers in two's complement representation).
- When shifting bits to the left, the rightmost bits are filled with zeros.