When to use Shift operators << >> in C#?

Junior Mayh&#233; picture Junior Mayhé · Dec 19, 2009 · Viewed 20.3k times · Source

I was studying shift operators in C#, trying to find out when to use them in my code.

I found an answer but for Java, you could:

a) Make faster integer multiplication and division operations:

*4839534 * 4* can be done like this: 4839534 << 2

or

543894 / 2 can be done like this: 543894 >> 1

Shift operations much more faster than multiplication for most of processors.

b) Reassembling byte streams to int values

c) For accelerating operations with graphics since Red, Green and Blue colors coded by separate bytes.

d) Packing small numbers into one single long...


For b, c and d I can't imagine here a real sample.

Does anyone know if we can accomplish all these items in C#? Is there more practical use for shift operators in C#?

Answer

GraemeF picture GraemeF · Dec 19, 2009

There is no need to use them for optimisation purposes because the compiler will take care of this for you.

Only use them when shifting bits is the real intent of your code (as in the remaining examples in your question). The rest of the time just use multiply and divide so readers of your code can understand it at a glance.