0

Is it possible to generate a unique hexadecimal hash from a string in LaTeX? It does not have to be cryptographic, so it doesn't matter if it is reversible. For example:

input: 2018013001
output: 78486F49

To explain my usecase: I would like to generate an unique identifier for my invoices. It should be generated out of a string containing the actual date and a number.

user5950
  • 1,456

2 Answers2

2

You have the binhex plain TeX macro package, or the xintbinhex package (from the xint bundle) for that. I completed with the nbaseprt package, which comes with numprint to format the hexadecimal representation of a number.

The \Hexadecimalnum command from fmtcount should be a third possibility – unfortunately, it doesn't work with such big numbers and produces only a four hexadecimal number. However, for your invoices, it might be OK, as it works up to 16⁵ – 1 = 1048575:

\documentclass{article}
\usepackage{ xintbinhex, nbaseprt}
\input{binhex}

 \begin{document}

\begin{tabular}{rclc}
2018013001 & $\rightarrow$ & \leavevmode\hex{2018013001} & \nbaseprint{\hex{2018013001}h}\\[2ex]
 & & \xintDecToHex{2018013001}
\end{tabular}

  \end{document} 

enter image description here

Bernard
  • 271,350
2

With just a few lines of codes you can define a macro that sets \invoiceid to the hexadecimal representation of the number.

I also show another one that also copes with letters in the string, using base 36.

\documentclass{article}
\usepackage{xparse}

\ExplSyntaxOn
\NewDocumentCommand{\makeinvoiceid}{m}
 {
  \tl_set:Nx \invoiceid
   {
    \int_to_Hex:n { #1 }
   }
 }

\NewDocumentCommand{\makeinvoicelongid}{m}
 {
  \invoice_add:nnn { #1 } {  1 } {  4 }
  \invoice_add:nnn { #1 } {  5 } {  8 }
  \invoice_add:nnn { #1 } {  9 } { 12 }
  \invoice_add:nnn { #1 } { 13 } { \tl_count:n { #1 } }
 }
\tl_new:N \invoicelongid
\cs_new_protected:Nn \invoice_add:nnn
 {
  \tl_put_right:Nx \invoicelongid
   {
    \int_to_Hex:n
     {
      \int_from_base:fn { \tl_range:nnn { #1 } { #2 } { #3 } } { 36 }
     }
   }
 }
\cs_generate_variant:Nn \int_from_base:nn { f }
\ExplSyntaxOff

\begin{document}

\makeinvoiceid{2018013001}

\invoiceid

\makeinvoicelongid{2018013AX001}

\invoicelongid

\end{document}

enter image description here

egreg
  • 1,121,712