[edit] C# Shift Operators
This section will discuss both C# bit shifting operators (<< and >>).
Here is a chart that describes the C# shift operators:
C# Shift Operators
|
Operator |
Name |
Description |
|
<< |
Left Shift |
Shifts bits to the left by specified number of bits |
|
>> |
Right Shift |
Shifts bits to the right by specified number of bits |
Example: Shift left
x = 4, y;
y = x << 3;
The code above will left shift the bit pattern of x. This is how you would do it.
4 = 1 0 0
1 0 0 //Bit pattern for 4
1 0 0 0 0 0 //Bits are shifted 3 times to the left
Notice: When bits are shifted 2 zeros are created
Example: C# Shift right
x = 5, y;
y = x >> 1;
The code above will right shift the bit pattern of x. This is how you would do it.
5 = 1 0 1
1 0 1 //Bit pattern for 5
0 1 0 //Shift to right 1 time. The last bit is lost.
Notice: When bits are shifted the trailing 1 falls off
Lets see this idea in some C# code:
using System;
class Test
{
static void Main()
{
//33 = 1 0 0 0 0 1
Console.WriteLine(33 >> 3);
//15 = 1 1 1 1
Console.WriteLine(15 << 2);
Console.Read();
}
}
OutPut:
|