Skip to content

Instantly share code, notes, and snippets.

@jd
Last active May 29, 2024 10:09
Show Gist options
  • Save jd/303809d1f6c6425cf5e9 to your computer and use it in GitHub Desktop.
Save jd/303809d1f6c6425cf5e9 to your computer and use it in GitHub Desktop.
Count trailing and leading zeroes in Python
def count_lead_and_trail_zeroes(d):
"""Count the number of leading and trailing zeroes in an integer."""
b = "{:064b}".format(d)
try:
return as_str.index("1"), 63 - as_str.rindex("1")
except ValueError:
return 64, 64
def count_lead_and_trail_zeroes(d):
# https://graphics.stanford.edu/~seander/bithacks.html#ZerosOnRightLinear
if d:
v = (d ^ (d - 1) >> 1) # Set v's trailing 0s to 1s and zero rest
trailing = 0
while v:
v >>= 1
trailing += 1
leading = 64
v = d
while v:
v >>= 1
leading -= 1
return leading, trailing
return 64, 64
@Aqendo
Copy link

Aqendo commented May 29, 2024

I know it is a gist from 2016, but since it shows up in google search I would like to clarify that the first function probably should have as_str replaced with b because as_str is undefined.

this is how it would look like:

def count_lead_and_trail_zeroes(d):
"""Count the number of leading and trailing zeroes in an integer."""
b = "{:064b}".format(d)
try:
return b.index("1"), 63 - b.rindex("1")
except ValueError:
return 64, 64

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment