Skip to content

Instantly share code, notes, and snippets.

@juanplopes
Created January 3, 2011 04:28
Show Gist options
  • Save juanplopes/763124 to your computer and use it in GitHub Desktop.
Save juanplopes/763124 to your computer and use it in GitHub Desktop.
public static class BitOperations
{
public static int PopCountIn(ulong value)
{
unchecked
{
const ulong mask0 = 0x0101010101010101;
const ulong mask1 = ~0ul / 3 << 1;
const ulong mask2 = ~0ul / 5;
const ulong mask3 = ~0ul / 17;
value -= (mask1 & value) >> 1;
value = (value & mask2) + ((value >> 2) & mask2);
value += value >> 4;
value &= mask3;
return (int)(((value * mask0) >> 56));
}
}
public static int HighestBitPosition(ulong value)
{
if (value == 0) return -1;
int position = 0;
if ((value & 0xFFFFFFFF00000000) != 0) position += 32;
if ((value & 0xFFFF0000FFFF0000) != 0) position += 16;
if ((value & 0xFF00FF00FF00FF00) != 0) position += 8;
if ((value & 0xF0F0F0F0F0F0F0F0) != 0) position += 4;
if ((value & 0xCCCCCCCCCCCCCCCC) != 0) position += 2;
if ((value & 0xAAAAAAAAAAAAAAAA) != 0) position += 1;
return position;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment