Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest way to get last significant bit position in a ulong (C#)?

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.

like image 698
Brans Ds Avatar asked May 07 '16 01:05

Brans Ds


1 Answers

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
like image 76
abelenky Avatar answered Oct 11 '22 19:10

abelenky