Thursday, July 23, 2020

converting between decimal and hex on the command line

I've never been on a *unix system without bc installed. (I was surprised recently as well that some Linux distributions do not include vi) Recently, I have had the need to convert decimal to hexadecimal and hexadecimal to decimal enough to warrant scripts.
#!/bin/sh
#dec2hex.sh
COMMAND=bc
if ! command -v $COMMAND &> /dev/null
then
    echo "$COMMAND could not be found"
    exit
fi 
echo "obase=16; $@" | $COMMAND

#!/bin/sh
#hex2dec.sh
COMMAND=bc
if ! command -v $COMMAND &> /dev/null
then
    echo "$COMMAND could not be found"
    exit
fi
echo "ibase=16; $@"|$COMMAND