• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1__all__ = ["popCount"]
2
3
4try:
5    bit_count = int.bit_count
6except AttributeError:
7
8    def bit_count(v):
9        return bin(v).count("1")
10
11
12"""Return number of 1 bits (population count) of the absolute value of an integer.
13
14See https://docs.python.org/3.10/library/stdtypes.html#int.bit_count
15"""
16popCount = bit_count
17
18
19def bit_indices(v):
20    """Return list of indices where bits are set, 0 being the index of the least significant bit.
21
22    >>> bit_indices(0b101)
23    [0, 2]
24    """
25    return [i for i, b in enumerate(bin(v)[::-1]) if b == "1"]
26