Shift. In C# this operator moves bit positions. It changes the bit representation of a type. The bits are shifted right (or left) a number of positions.
Operator notes. The C# language enables bitwise shifting with the right and left shift operators. With these operators, individual bits are all moved together.
Input and output. Consider a bit pattern that is part of an integer. We shift to the right several times (the arrows point in the shifting direction).
101
>> 1: 010
>> 1: 001
>> 1: 000
An example. We introduce a program that shows the right shift and then left shift bitwise operators in the C# language. We repeatedly apply them and change the value of an int.
Info The integer is shifted right zero places, then one place, and then two and more places.
Tip You can see that all numbers that are negative have the very leftmost (first) bit set to 1, while positive numbers have it set to 0.
Note The output of the program illustrates how the bit values are changed with the parameters to the shift operators.
Uses. Each time you use the Dictionary or Hashtable collection or call the GetHashCode method on a string, shift operators are used to acquire the hash code.
Tip You can use a right shift to implement divide by two on positive integral types.
Tip 2 If you are using a data structure that uses bitmasks, bit shifting can be used to guide the control flow.
Terms. The term "binary operators" is used to describe operators that receive two parameters. A "unary operator" receives only one argument.
Detail The term "bitwise operator" indicates an operator that receives one or two operands. It changes the bit representation.
Summary. We explored the shift operator and how it can be applied to change the value of an integer. The article provides a program to illustrate this clearly through a simulation.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jul 18, 2021 (edit).