If you want to know whether a particular bit is set in a byte, a simple AND mask can do the trick. I want to know if there is a faster way to achieve the same. As an example, bit shifting << or >> returns the shifted number rather than the bit that just ‘fell off’.
If there is no alternative in managed code, would writing unsafe assembly make it faster? If so, please explain how.
Context: This is for a complex algorithm that needs to be highly optimized for production code. I felt it necessary to clarify this to avoid the dreaded ‘do your own homework’ comments and/or vote downs.
As noted: bitwise operations are highly efficient. On any modern processor, virtually any such operation almost certainly executes in a single clock cycle.
If you want to see the actual code genn’ed for your expression, fire it up in the Visual Studio debugger. Set a breakpoint, when you hit it, click on menu: Debug..Windows..Disassembly.
Maybe, if your expression was sufficiently convoluted, you could beat the compiler and optimizer on this sort of thing, but I doubt it. More importantly, any performance issues you encounter are unlikely to be related to bit-twiddling. Don’t optimize until you have a problem. As James Michael Hare says:
More here:
See Bit-Twiddling Hacks for how to accomplish just about anything related to bit manipulation. Oriented towards the C language, but the same techniques work with little modification in C# (anything involving pointers might need some rethinking, for instance).