Skip to content

Instantly share code, notes, and snippets.

@sebgod
Created November 4, 2014 07:48
Show Gist options
  • Save sebgod/708b49b96fd7ce4a2791 to your computer and use it in GitHub Desktop.
Save sebgod/708b49b96fd7ce4a2791 to your computer and use it in GitHub Desktop.
Population count in C#
static int BitCount(uint value)
{
value = value - ((value >> 1) & 0x55555555); // reuse input as temporary
value = (value & 0x33333333) + ((value >> 2) & 0x33333333); // temp
value = ((value + (value >> 4) & 0xF0F0F0F) * 0x1010101) >> 24; // count
return unchecked((int)value);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment