What is the fastest(or at least very fast) way to get first set(1) bit position from least significant bit (LSB) to the most significant bit (MSB) in a ulong (C#)?
For ulong i = 18;
(10010) that would be 2(or 1 if we are counting position from 0).
MS C++ compiler has _BitScanForward64 Intrinsics for this task, but C# compiler doesn't have analogue.
As a bit-wise operation, the lowest set bit is:
ulong bit = x & ~(x-1);
and the original value with the lowest on-bit set to off is:
x & (x-1)
So to get all the bits that are on:
public static void Main()
{
ulong x = 13;
while(x > 0)
{
ulong bit = x & ~(x-1);
x = x & (x-1);
Console.WriteLine("bit-value {0} is set", bit);
}
}
Output
bit-value 1 is set
bit-value 4 is set
bit-value 8 is set
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With