Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get hexadecimal representation of an integer as string in Mathematica

Is there a built-in way in Mathematica to get the hexadecimal representation of a positive integer as a string (using letters of the alphabet as higher digits)? Currently I use my own implementation as

toHexString[n_Integer] := 
 StringJoin[
  ToString /@ 
   (IntegerDigits[n, 16] /. Thread[Range[10, 15] -> CharacterRange["A", "F"]])
 ]
like image 501
Szabolcs Avatar asked Apr 12 '11 15:04

Szabolcs


1 Answers

In[254]:= IntegerString[{16, 34, 110, 5676767}, 16]

Out[254]= {"10", "22", "6e", "569edf"}

or, if you don't like the standard lowercase characters in the result:

In[255]:= ToUpperCase[IntegerString[{16, 34, 110, 5676767}, 16]]

Out[255]= {"10", "22", "6E", "569EDF"}

Please note that IntegerString has an optional third argument that is very helpful in generating series of filenames that sort in the correct order when sorted alphabetically:

In[256]:= Table["filename" <> IntegerString[i, 10, 4] <> ".jpg", {i, 1, 7}]

Out[256]= {"filename0001.jpg", "filename0002.jpg", 
"filename0003.jpg", "filename0004.jpg", "filename0005.jpg", 
"filename0006.jpg", "filename0007.jpg"}
like image 163
Sjoerd C. de Vries Avatar answered Dec 05 '22 13:12

Sjoerd C. de Vries