Skip to content

Instantly share code, notes, and snippets.

@teslamint
Created May 13, 2011 12:58
Show Gist options
  • Save teslamint/970484 to your computer and use it in GitHub Desktop.
Save teslamint/970484 to your computer and use it in GitHub Desktop.
Hamming Weight
#include <iostream>
using namespace std;
const unsigned int m1 = 0x55555555; // 0101 0101 0101 0101 0101 0101 0101 0101
const unsigned int m2 = 0x33333333; // 0011 0011 0011 0011 0011 0011 0011 0011
const unsigned int m4 = 0x0f0f0f0f; // 0000 1111 0000 1111 0000 1111 0000 1111
void main() {
unsigned int a = 0x12345678; // 0001 0010 0011 0100 0101 0110 0111 1000
a = (a & m1) + ((a >> 1) & m1); // a = 0001 0001 0010 0100 0101 0101 0110 0100
a = (a & m2) + ((a >> 2) & m2); // a = 0001 0001 0010 0001 0010 0010 0011 0001
a = (a + (a >> 4)) & m4; // a = 0000 0010 0000 0011 0000 0100 0000 0100
a += a >> 8; // a = 0000 0010 0000 0011 0000 0111 0000 1000
a += a >> 16; // a = 0000 0010 0000 0011 0000 1001 0000 1100
a = a & 0x7f; // a = 0000 0000 0000 0000 0000 0000 0000 1100
cout << "# of 1 in a = " << a << endl;
system("pause");
}
@teslamint
Copy link
Author

from http://en.wikipedia.org/wiki/Hamming_weight
mixed popcount_1 and popcount_2

restriction: only operator EQUAL, NOT, INV, AND, XOR, OR, PLUS, LSHIFT, RSHIFT is allowed. total amount of operators is 40(equal operator is not counted in). recursive, repeat, conditional operation is disallowed. 32-bit.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment