Stream: ideas

Topic: Num.countLeadingZeros


view this post on Zulip Brendan Hansknecht (Mar 11 2023 at 17:08):

Not sure if we would want different names, but would it be fine to add Num.countLeadingZeros and Num.countTrailingZeros. They return the number of consecutive zero bits at the start or end of a number.

So for 0b0011_0000, countLeadingZeros would be 2 and countTrailingZeros would be 4.

view this post on Zulip Richard Feldman (Mar 11 2023 at 17:29):

both seem fine, although I'd try to get "bits" into the name

view this post on Zulip Richard Feldman (Mar 11 2023 at 17:29):

e.g. Num.countLeadingZeroBits or Num.leadingZeroBits

view this post on Zulip Richard Feldman (Mar 11 2023 at 17:30):

because otherwise a beginner might think that (for example) countTrailingZeroes 1_000_000 would return 6 :sweat_smile:

view this post on Zulip Joshua Warner (Mar 11 2023 at 20:07):

Fun fact, countTrailingZeroes 1_000_000 does return 6 :)

view this post on Zulip Richard Feldman (Mar 11 2023 at 20:07):

I wrote it down and then thought "what are the odds that by sheer coincidence....naaaaah I'm not gonna check"

view this post on Zulip Richard Feldman (Mar 11 2023 at 20:07):

so of COURSE it turned out to be the same :laughing:

view this post on Zulip Joshua Warner (Mar 11 2023 at 20:08):

Anything that's 10^n will have n trailing zeros when written in binary

view this post on Zulip Joshua Warner (Mar 11 2023 at 20:08):

(10 = 2*5, so you get exactly one factor of 2 per factor of 10)

view this post on Zulip Richard Feldman (Mar 11 2023 at 20:08):

ha, makes sense

view this post on Zulip Richard Feldman (Mar 11 2023 at 20:09):

ok well I'm sure there are numbers where it's different, e.g. (I'm also not bothering to check this :laughing:) 1_700_000 or maybe 1_070_000

view this post on Zulip Joshua Warner (Mar 11 2023 at 20:10):

Any number where when you lop off the zeros in base 10 still results in an even number, will differ in the number of zeros base 2 and base 10.

view this post on Zulip Joshua Warner (Mar 11 2023 at 20:10):

So actually neither of those examples work ;)

view this post on Zulip Richard Feldman (Mar 11 2023 at 20:13):

ok so...1_400_000

view this post on Zulip Joshua Warner (Mar 11 2023 at 20:13):

Bingo!

view this post on Zulip Joshua Warner (Mar 11 2023 at 20:13):

Anyway, this all reinforces the point that this could be super confusing

view this post on Zulip Richard Feldman (Mar 11 2023 at 20:14):

yeah I didn't even think of that - a lot of the time it would give the same answer by coincidence, so depending on which numbers you chose in test cases/local development, you might not even realize it until getting something in production :dizzy:


Last updated: Jun 16 2026 at 16:19 UTC