Shift operators are very useful while doing any mathematical operations in C#.
In C#, the shift operators are used to shift the bits of a binary number to the left or right. There are two types of shift operators.
1. Left Shift Operator
The left shift operator << shifts the bits of the number to the left and fills 0 on voids left as a result. The left operand specifies the value to be shifted, and the right operand specifies the number of positions that the bits in the value are to be shifted. Each shift to the left doubles the number, so it’s equivalent to multiplying the number by 2.
int number = 12; // Binary: 1100
// Left Shift Operator
int leftShift = number << 2; // Binary: 110000, Decimal: 48
Console.WriteLine("Left Shift: " + leftShift); // Output: Left Shift: 48
2. Right Shift Operator
The right shift operator >> shifts the bits of the number to the right. If the number is a type signed integer (int, long), the leftmost bit (sign bit) is replicated and filled on the left, otherwise, if the number is of type unsigned integer (unit, ulong), zero is filled on the left. Each shift to the right halves the number, so it’s equivalent to dividing the number by 2.
int number = 12; // Binary: 1100
// Right Shift Operator
int rightShift = number >> 2; // Binary: 11, Decimal: 3
Console.WriteLine("Right Shift: " + rightShift); // Output: Right Shift: 3
Here are some use cases for shift operators.
- Efficient Multiplication or Division: Shift operators can be used for quick multiplication or division by powers of two. For example, n << 1 is equivalent to n * 2, and n >> 1 is equivalent to n/ 2.
- Binary Serialization: Shift operators are useful in the binary serialization of data, where you convert data into a binary format for network transmission or to write to a file.
- Graphics Programming: In graphics programming, shift operators are often used for fast color manipulation and blending.
- Cryptography: In cryptographic algorithms, shift operators are used for various transformations and permutations on binary data1.