bit_length And bit_count Measure Integers
Size bitmasks and buffers with int.bit_length and int.bit_count: needed bits, popcount, and the Kernighan loop agree on every value shown.
Code
# 位掩码定量:bit_count 数 1 的个数,bit_length 给出容纳该值所需位数
READ, WRITE, EXECUTE = 0b100, 0b010, 0b001
mask = READ | EXECUTE
print("mask:", bin(mask), "| bit_count:", mask.bit_count(), "| bit_length:", mask.bit_length())
for n in (0, 1, 5, 255, 2**31):
print(f"{n}: bit_length={n.bit_length()} bit_count={n.bit_count()}")
# Kernighan 手写等价:每次清掉最低位的 1,循环次数即 popcount
def popcount_manual(n):
count = 0
while n:
n &= n - 1
count += 1
return count
print("manual == builtin:", popcount_manual(mask) == mask.bit_count())Output
Captured from a sandboxed run of this snippet in the build pipeline.
mask: 0b101 | bit_count: 2 | bit_length: 3
0: bit_length=0 bit_count=0
1: bit_length=1 bit_count=1
5: bit_length=3 bit_count=2
255: bit_length=8 bit_count=8
2147483648: bit_length=32 bit_count=1
manual == builtin: TrueInside the snippet
The working surface is the function popcount_manual — everything else is wiring.
Iteration happens inside for n in (0, 1, 5, 255, 2**31) — everything outside it runs once.
What to watch for
- Not one third-party dependency; every API call resolves in the runtime.
Using it
Declaration at the heart of the file: def popcount_manual(n)
Output lines are prefixed (mask:, manual == builtin:), and you can trace each step by its prefix alone.
popcount_manual is the public entry point; everything else in the file exists to support it.
Key statements
def popcount_manual(n):
count = 0
while n:
n &= n - 1
count += 1
return count
Interactive Tools for This Topic
FAQ
- Are there third-party dependencies?
- No. The dependency list is empty; the code stays inside the standard library. The file defines `popcount_manual` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.