C # uses the <(left shift) and> (right shift) operators to perform the shift operation.
Shift left (<)
Move the first operand to the left and the number of digits specified by the second operand.
The Left shift is equivalent to multiplication. The left shift is equivalent to multiplication 2; the left shift is equivalent to multiplication 4; The Left shift is equivalent to multiplication 8.
X <1 = x * 2
X <2 = x * 4
X <3 = x * 8
X <4 = x * 16
Similarly, the right shift is the opposite:
Shift right (>)
Move the first operand to the right to the number of digits specified by the second operand, and fill in 0 for the null position.
The right shift is equivalent to the entire division. The right shift is equivalent to dividing by 2; the right shift is equivalent to dividing by 4; The right shift is equivalent to dividing by 8.
X> 1 = x/2
X> 2 = x/4
X> 3 = x/8
X> 4 = x/16
When the C # shift operator is declared to be overloaded, the type of the first operand must always contain the class or structure declared by the operator, and the type of the second operand must always be int, for example:
Class Program
{
Static void Main (string [] args)
{
ShiftClass shift1 = new ShiftClass (5, 10 );
ShiftClass shift2 = shift1 <2;
ShiftClass shift3 = shift1> 2;
Console. WriteLine ("{0} <2 result: {1}", shift1.valA, shift2.valA );
Console. WriteLine ("{0} <2 result: {1}", shift1.valB, shift2.valB );
Console. WriteLine ("{0}> 2 result: {1}", shift1.valA, shift3.valA );
Console. WriteLine ("{0}> 2 result: {1}", shift1.valB, shift3.valB );
Console. ReadLine ();
}
Public class ShiftClass
{
Public int valA;
Public int valB;
Public ShiftClass (int valA, int valB)
{
This. valA = valA;
This. valB = valB;
}
Public static ShiftClass operator <(ShiftClass shift, int count)
{
Int a = shift. valA <count;
Int B = shift. valB <count;
Return new ShiftClass (a, B );
}
Public static ShiftClass operator> (ShiftClass shift, int count)
{
Int a = shift. valA> count;
Int B = shift. valB> count;
Return new ShiftClass (a, B );
}
}
}
The output result of the above expression is:
Because the displacement is faster than the multiplication and division speed, the efficiency requirement is high, and the multiplication and division operator that satisfies the power of 2 can be carried out by means of displacement.