I have learned about counters from here. My question is, can I have a counter in other than 10 base, say hexadecimal one? How do I achieve that?
2 Answers
You can use expl3:
\documentclass{article}
\usepackage{geometry} % to see more pages
\geometry{paperwidth=5cm,paperheight=5cm,bottom=2cm}
\ExplSyntaxOn
\NewExpandableDocumentCommand{\hexa}{m}
{
\egreg_hexa:c { c@#1 }
}
\cs_new:Npn \egreg_hexa:N #1 { \int_to_Hex:n { #1 } }
\cs_generate_variant:Nn \egreg_hexa:N { c }
\cs_set_eq:cN { @hexa } \egreg_hexa:N % for \pagenumbering
\ExplSyntaxOff
\newcounter{test}
\renewcommand{\thetest}{\hexa{test}}
\pagenumbering{hexa}
\begin{document}
\setcounter{page}{7}
\setcounter{test}{13}
\stepcounter{test}\thetest
\clearpage
\stepcounter{test}\thetest
\clearpage
\stepcounter{test}\thetest
\clearpage
\stepcounter{test}\thetest
\clearpage
\setcounter{test}{65566}\thetest
\end{document}
More generally, with any base up to 36
\documentclass{article}
\usepackage{geometry} % to see more pages
\geometry{paperwidth=5cm,paperheight=5cm,bottom=2cm}
\ExplSyntaxOn
\NewExpandableDocumentCommand{\cbase}{mm}
{
\egreg_cbase:nc { #1 } { c@#2 }
}
\cs_new:Npn \egreg_cbase:nN #1 #2 { \int_to_Base:nn { #2 } { #1 } }
\cs_generate_variant:Nn \egreg_cbase:nN { nc }
\NewDocumentCommand{\newrepresentation}{mm}
{% #1 = command name, #2 = base
\cs_new:Npn #1 ##1 { \cbase{#2}{##1} }
\cs_new:cpn { @\cs_to_str:N #1 } { \egreg_cbase:nN { #2 } }
}
\newrepresentation{\basexxxvi}{36}
\ExplSyntaxOff
\newcounter{test}
\renewcommand{\thetest}{\cbase{20}{test}}
\pagenumbering{basexxxvi}
\begin{document}
\raggedright
\setcounter{page}{33}
\setcounter{test}{17}
\stepcounter{test}\thetest, should be~I \ page~X
\clearpage
\stepcounter{test}\thetest, should be~J \ page~Y
\clearpage
\stepcounter{test}\thetest, should be~10 \ page~Z
\clearpage
\stepcounter{test}\thetest, should be~11 \ page~10
\clearpage
\setcounter{test}{65566}\thetest, should be~83I6 \ page~11
\end{document}
Here test is represented in base 20, while the page is represented in base 36. For page numbering, \newrepresentation is needed.
If lowercase letters are preferred, replace \int_to_Base:nn with \int_to_base:nn.
- 1,121,712
-
How about other base? For example I want my counter display in base 36... – Ngiap Sep 24 '23 at 15:02
-
I don't know if this is what you're after but:
\documentclass{article}
\usepackage{xparse}
\ExplSyntaxOn
\NewDocumentCommand{\tohex}{m}{\int_to_hex:n {#1}}
\ExplSyntaxOff
\begin{document}
\newcounter{mycounter}
\setcounter{mycounter}{43}
\tohex{\themycounter}
\end{document}
You could also convert to an arbitrary base (default 16) using
\documentclass{article}
\usepackage{xparse}
\ExplSyntaxOn
\NewDocumentCommand{\tobase}{O{16}m}{\int_to_base:nn {#2}{#1}}
\ExplSyntaxOff
\begin{document}
\newcounter{mycounter}
\setcounter{mycounter}{43}
\tobase[8]{\themycounter}
\end{document}
- 11,047


fmtcountpackage. – leandriis Oct 06 '19 at 16:37