add tag
Anonymous 1552
I want to plot a graph and I need to be able to count the number of trailing zeroes in the binary representation of integers from 1 to 100.  Can that be done in LaTeX or pgf or similar?

For example,

zeros(123) = 0

zeros(256) = 8
Top Answer
Using `expl3` one can first convert the integer to binary representation, than reverse the outcome and count the number of tokens until the first 1. The result gives the count of trailing zeros fully expandable.


\cs_new:Npn \TopAnswer_count_trailing_zeros:n #1
    \exp_last_unbraced:Ne \__TopAnswer_count_trailing_zeros_aux:w
      { \exp_args:Nf \tl_reverse:n { \int_to_bin:n { #1 } } } 1 \q_stop
\cs_new:Npn \__TopAnswer_count_trailing_zeros_aux:w #1 1 #2 \q_stop
    \tl_count:n { #1 }
\cs_new_eq:NN \trailingzeros \TopAnswer_count_trailing_zeros:n


Answer #2
The question can be read in two ways. Either you mean the digits, which are just given by the logarithm in basis 2, or really the trailing zeros. One can define functions for both interpretations.
\usepackage{pgf,pgffor} %pgffor only for the loop that is used in the illustration
	    \advance\c@pgf@counta by1%
\foreach \mynum in {1,12,123,1234,531,295}%
The binary representation of $\mynum$ is $\mybin$ and has $\mydig$ digits and
 no trailing zero%
 one trailing zero%
$\mytz$ trailing zeros%
![Screen Shot 2020-09-07 at 5.14.24 PM.png](/image?hash=971e2856f67e23f92071345a203166c50cd93581eb7819ff90d8bae3edfe1da5)

Notice that the trailing zero function does not have a sanity check, i.e. if you feed it with something that does not just consist of integers, you will get errors. As usual, one can add sanity checks at the expense of an increased complexity.

Enter question or answer id or url (and optionally further answer ids/urls from the same question) from

Separate each id/url with a space. No need to list your own answers; they will be imported automatically.