[Tex/LaTex] Convert hexadecimal string into (La)TeX number


How can I convert a user-supplied hexadecimal string like 14b or 14B into something which (La)TeX will recognise as a number? I suppose that a package like xcolor can do it, but I have not been able to find out how (Google is no help here). I'm aware of "XX but it only goes up to FF, or FFFF in XeTeX, and that's not enough in all cases for me. Converting to decimal during input is not really an option. Note that this is not about typesetting numbers in different forms but about converting a string argument representing a hex number into something which can be used in calculations.

Best Answer

The \int_from_hex:n function of expl3 accepts both uppercase and lowercase letters for the digits from A to F. So you can do


\cs_set_eq:NN \intfromhex \int_from_hex:n

and \Uchar\intfromhex{14b} or \Uchar\intfromhex{14B} will produce the same result.

Actually expl3 has its own version of \Uchar, but it's another topic.

If you need to do arithmetic, add also

\cs_set_eq:NN \inteval \int_eval:n

before \ExplSyntaxOff and something like


would work (here 36 is in decimal).

Note that 36+"14b would not work, because only uppercase letters are allowed in the " notation. Usage of \intfromhex converts to decimal.

Related Question