Skip to content

Instantly share code, notes, and snippets.

@Sibirtsev
Created September 5, 2016 04:59
Show Gist options
  • Save Sibirtsev/59809c2340ffca3f69caacd97f36ca8e to your computer and use it in GitHub Desktop.
Save Sibirtsev/59809c2340ffca3f69caacd97f36ca8e to your computer and use it in GitHub Desktop.
Count non-zero bits
def pop(x):
x = int(x)
x -= ((x >> 1) & int('0x55555555', 16))
x = (x & int('0x33333333', 16)) + ((x >> 2) & int('0x33333333', 16))
x = (x + (x >> 4)) & int('0x0F0F0F0F', 16)
x += (x >> 8)
x += (x >> 16)
return x & int('0x0000003F', 16)
x = int('0b10111100011000110111110111111', 2)
print 'x =',
print x
print 'count non-zero bits in x'
print 'result is ' + str(pop(int('0b10111100011000110111110111111', 2)))
x = '1' * 32
x = int('0b' + x, 2)
print 'result is ' + str(pop(x))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment