#!/usr/bin/python
import codecs
+import struct
def split_by_n( seq, n ):
"""A generator to divide a sequence into chunks of n units."""
def bits_set_count(x):
"""
Accepts bytes as input and returns the number of bits set in the bytes.
+ For performance optimization, len(x) must be a multiple of 8!
"""
- if type(x) == bytes:
- sum = 0
- for b in x:
- sum += bin(b).count('1')
- return sum
- if type(x) == int:
- return bin(x).count('1')
- else:
- raise TypeError()
+ assert len(x)%8 == 0
+ s = 0
+ for n in struct.unpack('Q'*(len(x)//8), x):
+ s += bin(n).count('1')
+ return s