Search code examples
c#bit-manipulationperformance

Efficient bitwise operation to find the index of the left|right most bit set


In C++ I can use compiler specific intrisics to find the left|right most bit set, like shown in this thread.

Is there anything similar in C#? Or I need to iterate over all the bits to achieve that?


Solution

  • There is no access to compiler-specific "builtin" instructions for things like ffs. You would have to use a regular code implementation using things like bitmasks and shift operations. However, that doesn't necessarily mean you need to iterate over all the bits: there are some scary-clever "regular" implementations for many of these methods, doing crazy "add some bizarre constant that isn't obvious" that are designed to cut out most of the branching and iteration, and which would be perfectly fine in C#. The main thing to keep in mind if you port one of these is knowing whether it is using "signed" or "unsigned" right-shifts; if it is using "signed" use int (etc); if it is "unsigned", use uint (etc).