Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to use RightShift Operators in C#?
The right shift operator (>>) in C# moves the bits of the left operand to the right by the number of positions specified by the right operand. This operation effectively divides the number by powers of 2.
Syntax
Following is the syntax for the right shift operator −
result = operand >> numberOfPositions;
Where operand is the value whose bits will be shifted, and numberOfPositions specifies how many positions to shift right.
How Right Shift Works
The right shift operator moves each bit to the right by the specified number of positions. For positive numbers, zeros are filled in from the left. Each right shift by 1 position divides the number by 2 (integer division).
Using Right Shift Operator
Example
using System;
class Program {
static void Main(string[] args) {
int a = 60; /* 60 = 0011 1100 */
int b = 0;
b = a >> 2; /* 15 = 0000 1111 */
Console.WriteLine("Original value: " + a);
Console.WriteLine("Right Shift by 2: " + b);
// More examples
Console.WriteLine("60 >> 1 = " + (60 >> 1)); // 30
Console.WriteLine("60 >> 3 = " + (60 >> 3)); // 7
Console.WriteLine("100 >> 4 = " + (100 >> 4)); // 6
}
}
The output of the above code is −
Original value: 60 Right Shift by 2: 15 60 >> 1 = 30 60 >> 3 = 7 100 >> 4 = 6
Right Shift with Negative Numbers
For negative numbers, the behavior depends on the sign bit. In C#, arithmetic right shift is performed, meaning the sign bit is preserved −
Example
using System;
class Program {
static void Main(string[] args) {
int positive = 16;
int negative = -16;
Console.WriteLine("Positive number:");
Console.WriteLine("16 >> 2 = " + (positive >> 2));
Console.WriteLine("\nNegative number:");
Console.WriteLine("-16 >> 2 = " + (negative >> 2));
// Binary representation
Console.WriteLine("\nBinary representation:");
Console.WriteLine("16 in binary: " + Convert.ToString(16, 2).PadLeft(8, '0'));
Console.WriteLine("16 >> 2: " + Convert.ToString(16 >> 2, 2).PadLeft(8, '0'));
}
}
The output of the above code is −
Positive number: 16 >> 2 = 4 Negative number: -16 >> 2 = -4 Binary representation: 16 in binary: 00010000 16 >> 2: 00000100
Common Use Cases
-
Fast Division: Right shift by n positions divides by 2^n (for positive integers).
-
Bit Manipulation: Extracting specific bits or reducing bit patterns.
-
Performance Optimization: Right shift is faster than division for powers of 2.
Conclusion
The right shift operator (>>) in C# moves bits to the right by specified positions, effectively performing fast integer division by powers of 2. It's particularly useful for bit manipulation and performance-critical operations where division by powers of 2 is needed.
