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
Bitwise right shift operators in C#
The bitwise 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 bitwise right shift operator −
result = operand >> numberOfPositions;
How It Works
When you right shift a binary number, each bit moves to the right by the specified number of positions. Vacant positions on the left are filled with zeros for positive numbers and ones for negative numbers (sign extension).
Example
The following example demonstrates the bitwise right shift operator −
using System;
class Program {
static void Main() {
int a = 60; // 60 = 0011 1100 in binary
int result;
result = a >> 2; // Right shift by 2 positions
Console.WriteLine("Original value: {0} (binary: {1})", a, Convert.ToString(a, 2).PadLeft(8, '0'));
Console.WriteLine("After right shift by 2: {0} (binary: {1})", result, Convert.ToString(result, 2).PadLeft(8, '0'));
// Additional examples
Console.WriteLine("\nMore examples:");
Console.WriteLine("40 >> 1 = {0}", 40 >> 1); // 40/2 = 20
Console.WriteLine("100 >> 3 = {0}", 100 >> 3); // 100/8 = 12
Console.WriteLine("16 >> 4 = {0}", 16 >> 4); // 16/16 = 1
}
}
The output of the above code is −
Original value: 60 (binary: 00111100) After right shift by 2: 15 (binary: 00001111) More examples: 40 >> 1 = 20 100 >> 3 = 12 16 >> 4 = 1
Right Shift with Negative Numbers
When right shifting negative numbers, the sign bit is preserved (arithmetic right shift) −
using System;
class Program {
static void Main() {
int negativeValue = -8;
int result = negativeValue >> 2;
Console.WriteLine("Original: {0}", negativeValue);
Console.WriteLine("After right shift by 2: {0}", result);
Console.WriteLine("Binary representation preserved the sign bit");
}
}
The output of the above code is −
Original: -8 After right shift by 2: -2 Binary representation preserved the sign bit
Common Use Cases
| Use Case | Example | Description |
|---|---|---|
| Fast Division by Powers of 2 |
value >> 1 (divide by 2) |
More efficient than regular division |
| Extracting Higher Bits | color >> 8 |
Get upper byte from a 16-bit value |
| Binary Data Processing | flags >> 4 |
Process bit flags and masks |
Conclusion
The bitwise right shift operator (>>) moves bits to the right and is commonly used for fast division by powers of 2 and binary data manipulation. Remember that right shifting by n positions is equivalent to dividing by 2n, making it a performance-efficient operation for certain calculations.
