Getting Bit Information for a Number in CSharp

This is a class I wrote to help someone out on the MSDN forums.  It returns information about the bits set in a number. The numbers returned are zero based indexes from the least significant bit to the most significant (right to left)

 

public class BitStats

{

public int HighestSetBit { get; set; }

public int LowestSetBit { get; set; }

public int HighestZeroBit { get; set; }

public int LowestZeroBit { get; set; }

public int NumberOfBitsSet { get; set; }

public int NumberOfZeroBits { get; set; }

public static BitStats GetBitStats(int value)

{

return GetBitStats((ulong)value, sizeof(int) * 8);

}

public static BitStats GetBitStats(short value)

{

return GetBitStats((ulong)value, sizeof(short) * 8);

}

public static BitStats GetBitStats(long value)

{

return GetBitStats((ulong)value, sizeof(long)*8);

}

private static BitStats GetBitStats(ulong value, int bits)

{

ulong newValue = value;

BitStats stats = new BitStats();

stats.HighestSetBit = stats.HighestZeroBit = stats.NumberOfBitsSet = 0;

stats.LowestSetBit = stats.LowestZeroBit = bits + 1;

for (int x = 0; x < bits; x++)

{

bool bit = (newValue % 2 == 1);

newValue = newValue / 2;

if (bit)

{

stats.NumberOfBitsSet += 1;

stats.HighestSetBit = x;

stats.LowestSetBit = Math.Min(x, stats.LowestSetBit);

}

else

{

stats.LowestZeroBit = Math.Min(x, stats.LowestZeroBit);

stats.HighestZeroBit = x;

stats.NumberOfZeroBits += 1;

}

}

return stats;

}

}

Advertisements
This entry was posted in Utility. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s