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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Jul 18, 2021 (edit).