public int HammingWeight(uint n) {
int count = 0;
while(n != 0)
{
count += (int)(n & 1);
n >>= 1;
}
return count;
}
A straightforward solution

+1. Added some comments:
public int HammingWeight(uint n) { int numOnes = 0; while (n != 0) { // ex: 00000000000000000000000000001011 and'd with // 00000000000000000000000000000001 // will be 00000000000000000000000000000001 // so numOnes will increment by 1. numOnes += (int)(n & 1); // rightshift assignment. shifts n's bits to the right by 1 and stores it in n. n >>= 1; } return numOnes; }