Table of Contents
The right shift operator (>>) shifts the bits of the left operand to the right by the number of positions specified by the right operand. Each right shift moves the bits toward the less significant positions. For unsigned integers, zeros are inserted into the vacated most significant bit positions.
For positive integers, shifting right by one position is generally equivalent to dividing the value by 2 and discarding any remainder. Right shift operations are commonly used in bit manipulation, embedded programming, and low-level software development.
Source Code #
#include <iostream>
int main()
{
int number = 20;
int result = number >> 2;
std::cout << "Original Value: " << number << '\n';
std::cout << "Shifted Value : " << result << '\n';
return 0;
}
Output #
Original Value: 20
Shifted Value : 5
Explanation #
- The right shift operator (
>>) shifts the bits of the left operand to the right by the specified number of positions. number >> 2shifts every bit ofnumbertwo positions toward the less significant bits.- The binary representation of
20is:20 = 00010100â‚‚ - After shifting right by two positions:
00010100â‚‚ >> 2 = 00000101â‚‚ - The binary value
00000101â‚‚is equal to the decimal value5. - For positive integers, shifting right by one position generally divides the value by 2 while discarding any fractional part.
- The behavior of right shifting negative signed integers is implementation-defined, so portable programs should avoid relying on it.
return 0;terminates the program successfully.