# Use character code of macro parameter

How can the character code of a character received as a macro parameter be obtained?

As an example: In the MWE below, \letterwithnum{<n>} produces the n-th letter in the alphabet. \getletternum{<letter>} is supposed to do the opposide, but \# is converted to 35 and the parameter replacement doesn't happen. How can I fix this?

\documentclass{article}

\def\letterwithnum#1{%
\char\numexpr\a-1+#1\relax%
}

\def\getletternum#1{%
\the\numexpr\#1-\a+1\relax%
}

\begin{document}

\letterwithnum{11} % -> k

\getletternum{k} % -> 351-1 with error

\end{document}


Just using #1 will work. Also the backslash in \a can be omitted. There are two ways for denoting an alphabetic constant:

<char>
\<char>


that is, the backquote can be followed by a macro with a one character name; such a macro is not interpreted as such, in this case, but is just a way to escape the character. It's only necessary for some special characters

\ # %


and some other that need the ^^ notation, such as

^^M ^^?


Thus, if you want to get the character code of ^^M, you need

\^^M


(it is 13, by the way). You can't input %, so \% is necessary and similarly for the backslash.

For letters the backslash is not needed, so you code can also be

\def\letterwithnum#1{%
\char\numexpra-1+#1\relax
}

\def\getletternum#1{%
\the\numexpr#1-a+1\relax
}


And \newcommand should be used with LaTeX.

I can also suggest using predefined functions:

\documentclass{article}
\usepackage{xparse}

\ExplSyntaxOn

\NewExpandableDocumentCommand{\letterfromnum}{m}
{
\int_to_alph:n { #1 }
}

\NewExpandableDocumentCommand{\getletternum}{m}
{
\int_from_alph:n { #1 }
}

\ExplSyntaxOff

\begin{document}

\letterfromnum{11} should print k

\getletternum{k} should print 11

\end{document}


Just use #1, instead of \#1.

\documentclass{article}

\def\letterwithnum#1{%
\char\numexpr\a-1+#1\relax%
}

\def\getletternum#1{%
\the\numexpr#1-\a+1\relax%
}

\begin{document}

\letterwithnum{11} % -> k

\getletternum{k} % -> 351-1 with error

\end{document}