#74 – Shift Operators

C# supports two bitwise shift operators that allow you to shift a series of bits a certain number of bit positions to the left or right.

  • <<    Left shift
  • >>    Right shift

The shift operators work on the following types: uint, int, ulong, and long.

 uint u = 0x32 << 4;    // Shift 4 bits to left = 0x320
 uint u2 = 0xAB0 >> 4;  // Shift 4 bits to right = 0xAB

Note that shifting to the left is the same as multiplying the value by 2 to the power of the # of bits shifted.  E.g. Shifting by 1 bit doubles the number and shifting by 2 bits multiples the number by 4.

 uint u = 12 << 1;      // 24
 u = u << 3;            // * 8 = 192

Similarly, shifting to the right divides the value by 2 to the power of the # of bits shifted.

Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

2 Responses to #74 – Shift Operators

  1. Pingback: #75 – New Bits When Shifting « 2,000 Things You Should Know About C#

  2. kai zhou says:

    Lessons learned, good job, thanks Sean.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: