views:

500

answers:

4
+3  A: 

Check out these Wikipedia articles about the binary number system and the arithmetic shift. I think they will answer your questions.

The shift operators are rarely encountered in business applications today. They will appear frequently in low-level code that interacts with hardware or manipulates packed data. They were more common back in the days of 64k memory segments.

cdonner
Packed data is still pretty common, but C# programmers should use BitConverter (not BinaryReader) or BitVector for development. Only if that code is verified as a performance problem would you go back and rewrite with explicit bit manipulation operators.
Ben Voigt
"pretty common" is a relative term. The last time I worked with packed data was in 1992, I think, when I had to fit the coordinates of 8000 stars into a single data segment.
cdonner
+10  A: 

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.

GraemeF
Thank you for the comment Graeme! I understand your point
Junior Mayhé
+4  A: 

Unless there is a very compelling reason, my opinion is that using clever tricks like that typically just make for more confusing code with little added value. The compiler writers are a smart bunch of developers and know a lot more of those tricks than the average programmer does. For example, dividing an integer by a power of 2 is faster with the shift operator than a division, but it probably isn't necessary since the compiler will do that for you. You can see this by looking at the assembly that both the Microsoft C/C++ compiler and gcc perform these optimizations.

Mark Wilkins
A: 

when to use them? never.

you can use the for shifting and assembeling binary numbers. you shouldnt use them for any sort of smartass magic. newer programmers wont understand that, and it wont give you any advantage.

b) Reassembling byte streams to int values

use binary reader

Hellfrost