Skip to content

Integer bit counts and bit lengths [ref]

Problem

  • Count set bits in 0b1011.
  • Find the bit lengths of 0, 7, and 8.
  • Count differing bits between 5 and 1.
  • Remove one set bit per iteration from 0b1011 and count iterations.
  • Format 11 in binary with and without its prefix.

Python solution

(0b1011).bit_count()  # 3

[(x).bit_length() for x in (0, 7, 8)]  # [0, 3, 4]

(5 ^ 1).bit_count()  # 1

n, count = 0b1011, 0
while n:
    n &= n - 1
    count += 1
count  # 3

bin(11)          # '0b1011'
format(11, "b")  # '1011'