intTools.py 586 B

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