There are a lot of questions about this on StackOverflow. A lot. However I cannot find an answer that:
- Works in C#
- Works for 64-bit integers (as opposed to 32-bit)
Faster than:
private static int Obvious(ulong v)
{
int r = 0;
while ((v >>= 1) != 0)
{
r++;
}
return r;
}
Or even
int r = (int)(Math.Log(v,2));
I'm assuming a 64-bit Intel CPU here.
One useful reference is the Bit Hacks page and another is fxtbook.pdf
However, while these gives useful direction to approach the problem, they do not give a ready answer.
I'm after a re-usable function that can do something similar to _BitScanForward64 and _BitScanReverse64 only for C#.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…