Convert a decimal number to hexadecimal from Bash

Posted on

As for the faq with the conversion to binary, also in this we make use of the fantastic bash braces extensions to convert to hexadecimal.

So, always considering the bash faq on the binary we start initially by converting a decimal number between 0 and 255 which corresponds to a hexadecimal digit between 0 and FF:

hex=({{0..9},{a..f}}{{0..9},{a..f}})
echo ${hex[*]}
how to convert a decimal number to hexadecimal with bash
bash- hexadecimal number of array

At this point to get the result of the number 200 or 21 is enough

echo ${hex[200]}
c8
echo ${hex[21]}
15

If the range of the hexadecimal number changes, for example if we double or quadruple it is enough that we define the hex variable with one or two more blocks of the type {0..9}, {a..f}.

So summing up, the hex variable will have to contain many blocks {0..9}, {a..f} based on the maximum binary number to be obtained, that is, if the maximum number is 16n -1 then it will take n groups {0. .9}, {a..f}.

As an example if n=4 and therefore 164 -1=65535 the blocks will be 4

hex=({{0..9},{a..f}}{{0..9},{a..f}}{{0..9},{a..f}}{{0..9},{a..f}})
echo ${hex[60000]}
ea60
echo ${hex[37]}
0025

Leave a Reply

Your email address will not be published. Required fields are marked *