Skip to content

Instantly share code, notes, and snippets.

@nicksloan
Forked from anonymous/bits.py
Created May 21, 2013 16:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nicksloan/5621251 to your computer and use it in GitHub Desktop.
Save nicksloan/5621251 to your computer and use it in GitHub Desktop.
import random
data = list()
for i in range(10000):
data.append(random.randint(0, 2**32))
bits_set = {0: 0}
for i in range(256):
bits_set[i] = (i & 1) + bits_set[i / 2]
def count_ones(x):
return (
bits_set[x & 255] + bits_set[(x >> 8) & 255] +
bits_set[(x >> 16) & 255] + bits_set[(x >> 24) & 255])
for x in data:
print '%s: %s: %s' % (x, bin(x), count_ones(x))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment