I need a fast way to count the number of bits in an integer in python. My current solution is
bin(n).count("1")
but I am wondering if there is any faster way of doing this?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
For arbitrary-length integers,
bin(n).count("1")is the fastest I could find in pure Python.I tried adapting Óscar’s and Adam’s solutions to process the integer in 64-bit and 32-bit chunks, respectively. Both were at least ten times slower than
bin(n).count("1")(the 32-bit version took about half again as much time).On the other hand, gmpy
popcount()took about 1/20th of the time ofbin(n).count("1"). So if you can install gmpy, use that.To answer a question in the comments, for bytes I’d use a lookup table. You can generate it at runtime:
Or just define it literally:
Then it’s
counts[x]to get the number of 1 bits inxwhere 0 ≤ x ≤ 255.