Thursday, April 12, 2012

Bash Recipes Part 3 - Converting between decimal and hexadecimal

     People who work with computer systems would have encountered the problem of converting between decimal and hexadecimal numbers one time or the other.  Here is a bash solution for it

function decToHex()
{
DEC=${1?You should provide an argument}
echo $DEC|grep -q -E "^[0-9]+$" || { echo "The argument is not a decimal"; return 1 ; }
printf "%x\n" ${DEC}
}

function hexToDec()
{
HEX=${1?You should provide an argument}
echo $HEX|grep -q -E "^[0-9a-fA-F]+$" || { echo "The argument is not a hexadecimal"; return 1 ; }
printf "%d\n" 0x${HEX}
}

A few examples

safeer@penguinpower:~$ decToHex 10
a
safeer@penguinpower:~$ hexToDec a
10
safeer@penguinpower:~$ decToHex 1234
4d2
safeer@penguinpower:~$ hexToDec abc
2748

No comments:

Post a Comment