2

Background: I'm trying to write an L3 function which returns the nth digit from a given number's binary expansion. Getting this to work, however, has been very frustrating.

\documentclass{article}
\usepackage{expl3}
\begin{document}
\ExplSyntaxOn

\tl_new:N \tl_bin % set up variable to store binary digits

\cs_new:Npn \get_bin_digit:nn #1#2 {
    \tl_set:Nn \tl_bin {\int_to_bin:n {#1}} % store binary expansion in our variable
    \tl_item:Nn \tl_bin {#2} % index into the variable storing the binary expansion
}

\get_bin_digit:nn{5}{2}

\ExplSyntaxOff
\end{document}

The expected behavior is that the function call should output "0". The second digit in the binary expansion of the number 5, 101, is 0. However, instead the result I get is ''5''. I have no idea what's going on here!

5

You have to expanded the result of \int_to_bin:n using \tl_set:Nx. If you do only

\tl_set:Nn \tl_bin {\int_to_bin:n {#1}}

the result in \tl_bin will literally be \int_to_bin:n {5}. If you count from the left then the first token is \int_to_bin:n and the second is 5 (braces are ignored).

Also, your function is performing an assignment and should therefore be protected.

\documentclass{article}
\usepackage{expl3}
\begin{document}
\ExplSyntaxOn

\tl_new:N \tl_bin % set up variable to store binary digits

\cs_new_protected:Npn \get_bin_digit:nn #1#2 {
  \tl_set:Nx \tl_bin {\int_to_bin:n {#1}} % store binary expansion in our variable
  \tl_item:Nn \tl_bin {#2} % index into the variable storing the binary expansion
}

\get_bin_digit:nn{5}{2}

\ExplSyntaxOff
\end{document}

To save some typing and the temporary variable you could also define a variant of \tl_item:nn which expands the first argument.

\documentclass{article}
\usepackage{expl3}
\begin{document}
\ExplSyntaxOn

\cs_generate_variant:Nn \tl_item:nn { xn }

\cs_new_protected:Nn \get_bin_digit:nn
  {
    \tl_item:xn { \int_to_bin:n { #1 } } { #2 }
  }

\get_bin_digit:nn { 5 } { 2 }

\ExplSyntaxOff
\end{document}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.