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
Skillmon
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.

```
\documentclass[]{article}

\ExplSyntaxOn
\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
\ExplSyntaxOff

\begin{document}
\trailingzeros{123}

\trailingzeros{256}
\end{document}
```
Answer #2
marmot
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.
```
\documentclass{article}
\usepackage{geometry}
\usepackage{pgf,pgffor} %pgffor only for the loop that is used in the illustration
\pgfmathdeclarefunction{binarydigits}{1}{%
\begingroup%
\pgfmathparse{int(1+ln(#1)/ln(2))}%
\pgfmathsmuggle\pgfmathresult\endgroup%
}%
\makeatletter
\pgfmathdeclarefunction{trailingzeros}{1}{%
  \begingroup%
	\c@pgf@counta=0%
    \expandafter\pgfmath@trailingzeros@i#1\pgfmath@token@stop
    \edef\pgfmathresult{\the\c@pgf@counta}%
    \pgfmathsmuggle\pgfmathresult%
  \endgroup}
\def\pgfmath@trailingzeros@i#1{%
    \ifx\pgfmath@token@stop#1%
    \else
	  \ifnum#1=0\relax
	    \advance\c@pgf@counta by1%
	  \else
	    \c@pgf@counta0%
	  \fi	
      \expandafter\pgfmath@trailingzeros@i
    \fi}  
\makeatother
\begin{document}
\foreach \mynum in {1,12,123,1234,531,295}%
{\pgfmathsetmacro{\mybin}{bin(\mynum)}%
\pgfmathsetmacro{\mydig}{binarydigits(\mynum)}%
\pgfmathsetmacro{\mytz}{trailingzeros(bin(\mynum))}%
\pgfmathtruncatemacro{\itest}{min(trailingzeros(bin(\mynum)),2)}%
The binary representation of $\mynum$ is $\mybin$ and has $\mydig$ digits and
\ifcase\itest
 no trailing zero%
\or 
 one trailing zero%
\or
$\mytz$ trailing zeros%
\fi.\par}
\end{document}
```
![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.