Alan Bawden ha scritto:
If you like this sort of stuff, check out the book "Hacker's Delight" by
Henry Warren.  See<https://en.wikipedia.org/wiki/Hacker%27s_Delight>.

Thank you for your suggestion. Really interesting. Just for fun I tried
to port the function to 64 bit:

def bit_count_64(n):
       lt = n >> 62
       n &= (~(0x3f << 62)) & ((1 << 63) - 1)
       n = (n - ((n >> 1) & 0o333333333333333333333)
              - ((n >> 2) & 0o111111111111111111111))
       n = (   (n & 0o307070707070707070707)
            + ((n & 0o070707070707070707070) >> 3))
       return (n % 63) + (0, 1, 1, 2)[lt]

n=0xffffffffffffffff
bit_count_64(n)
64

n=0x3ffffffffffffffe
bit_count_64(n)
61

bit_count_64(1 << 63)
1

...in C it would have been simpler :^)

--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to