_BitScanForward in C#?

Intrinsic functions aren't in any library, they're implemented inside the CPU, the compiler emits the machine code which the CPU recognizes as evoking this particular behavior.

They're a way of getting access to instructions that don't have a simple C equivalent.

Until the .NET optimizer becomes smart enough to recognize them (for example, the Mono JIT recognizes some SIMD instructions, encoded in MSIL as calls to functions of a particular class, similarly the .NET JIT replaces calls to System.Math methods with floating-point operations), your C# code is doomed to run an order of magnitude slower than the original C++.


The _BitScanForward C++ function is an intrinsic compiler function. It finds the first on bit in a sequence of bytes searching from the lowest order bit to the highest and returning the value of the bit. You could probably implement something similar using bit manipulation tactics in C# (though it'll never come close to the same performance). If you're comfortable with bit manipulation in C++ then its basically the same in C#.


_BitScanForward searches for the first set bit in an integer, starting from the least significant bit searching towards the most significant bit. It compiles to the bsf instruction on the x86 platform.

The bit twiddling hacks page includes a handful of potential replacement algorithms that excel in different situations. There's an O(N) function (that half the time with uniformly-distributed inputs returns with only one iteration) and some sub-linear options, and some that make use of multiplication steps. Picking one might not be trivial, but any should work.

Tags:

C#

.Net

C++

Pinvoke