Consolidate bit_count / popCount methods
Fixes https://github.com/fonttools/fonttools/issues/2331
This commit is contained in:
parent
35dae02dea
commit
f64f0b42f2
@ -1,28 +1,14 @@
|
|||||||
__all__ = ['popCount']
|
__all__ = ['popCount']
|
||||||
|
|
||||||
|
|
||||||
def popCount(v):
|
try:
|
||||||
"""Return number of 1 bits (population count) of an integer.
|
bit_count = int.bit_count
|
||||||
|
except AttributeError:
|
||||||
|
def bit_count(v):
|
||||||
|
return bin(v).count('1')
|
||||||
|
|
||||||
If the integer is negative, the number of 1 bits in the
|
"""Return number of 1 bits (population count) of the absolute value of an integer.
|
||||||
twos-complement representation of the integer is returned. i.e.
|
|
||||||
``popCount(-30) == 28`` because -30 is::
|
|
||||||
|
|
||||||
1111 1111 1111 1111 1111 1111 1110 0010
|
See https://docs.python.org/3.10/library/stdtypes.html#int.bit_count
|
||||||
|
"""
|
||||||
Uses the algorithm from `HAKMEM item 169 <https://www.inwap.com/pdp10/hbaker/hakmem/hacks.html#item169>`_.
|
popCount = bit_count
|
||||||
|
|
||||||
Args:
|
|
||||||
v (int): Value to count.
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
Number of 1 bits in the binary representation of ``v``.
|
|
||||||
"""
|
|
||||||
|
|
||||||
if v > 0xFFFFFFFF:
|
|
||||||
return popCount(v >> 32) + popCount(v & 0xFFFFFFFF)
|
|
||||||
|
|
||||||
# HACKMEM 169
|
|
||||||
y = (v >> 1) & 0xDB6DB6DB
|
|
||||||
y = v - y - ((y >> 1) & 0xDB6DB6DB)
|
|
||||||
return (((y + (y >> 3)) & 0xC71C71C7) % 0x3F)
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user