bash ascii to hex

Pure BASH convertor of string to printable hexadecimal sequence and back

str2hex_echo() {
    # USAGE: hex_repr=$(str2hex_echo "ABC")
    #        returns "0x410x420x43"
    local str=${1:-""}
    local fmt="0x%x"
    local chr
    local -i i
    for i in `seq 0 $((${#str}-1))`; do
        chr=${str:i:1}
        printf  "${fmt}" "'${chr}"
    done
}

hex2str_echo() {
    # USAGE: ASCII_repr=$(hex2str_echo "0x410x420x43")
    #        returns "ABC"
    echo -en "'${1:-""//0x/\\x}'"
}

EXPLANATION

ASCII->hex: The secret sauce of efficient conversion from character to its underlying ASCII code is feature in printf that, with non-string format specifiers, takes leading character being a single or double quotation mark as an order to produce the underlying ASCII code of the next symbol. This behavior is documented in GNU BASH reference, but is also exposed in details together with many other other wonderful utilities in Greg's (also known as GreyCat's) wiki page BashFAQ/071 dedicated to char-ASCII conversions.


You have several options

$ printf hello | xxd
0000000: 6865 6c6c 6f                             hello

See also: Ascii/Hex convert in bash


$ str="hello"
$ hex=$(xxd -pu <<< "$str")
$ echo "$hex"
6C6C6568A6F

Or:

$ hex=$(hexdump -e '"%X"' <<< "$str")
$ echo "$hex"
6C6C6568A6F

Careful with the '"%X"'; it has both single quotes and double quotes.

Tags:

Ascii

Hex

Bash