Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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#?

like image 924
Junior Mayhé Avatar asked Dec 19 '09 17:12

Junior Mayhé


People also ask

What are operators << and >> used for?

C++ Arithmetic Operators Arithmetic operators are used to perform arithmetic operations on variables and data. For example, a + b; Here, the + operator is used to add two variables a and b .

What is the use of << shift operator?

The left shift operator ( << ) shifts the first operand the specified number of bits, modulo 32, to the left. Excess bits shifted off to the left are discarded. Zero bits are shifted in from the right.

What is the use of >> in C programming?

Bitwise Right shift operator >> is used to shift the binary sequence to right side by specified position.

How does << operator work in C?

It is represented by '<<' sign. It is used to shift the bits of a value to the left by adding zeroes to the empty spaces created at the right side after shifting. The bits of first operand are shifted to the left by the number of positions specified by the second operand.


1 Answers

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.

like image 104
GraemeF Avatar answered Sep 17 '22 13:09

GraemeF