Pure bash, without loop Ascii <-> Hex convertion
1. Ascii to Hexadecimal conversion in bash
Very quick and short:
string='Hello World.' oIFS="$IFS" IFS=$'\n' printf '%02X\n' ${string//?/$'\n'\'&}; IFS="$oIFS"
Will produce:
48 65 6C 6C 6F 20 57 6F 72 6C 64 2E
Yes, in order to handle space, we have to play with $IFS.
1.1. Into an variable of type array:
string='Hello World.' oIFS="$IFS" IFS=$'\n' printf -v string '%02X\n' ${string//?/$'\n'\'&}; IFS="$oIFS" mapfile -t array <<<${string%$'\n'} echo ${array[@]@Q}
'48' '65' '6C' '6C' '6F' '20' '57' '6F' '72' '6C' '64' '2E'
1.2. Better into a function to populate an array:
In a function, we could localize $IFS, things become a little simplier.
ascii2hex() { local _varname=$1 _string=${*:2} IFS=$'\n' printf -v _string '%02X\n' ${_string//?/$'\n'\'&} mapfile -t "$_varname" <<<${_string%$'\n'} } ascii2hex myArray 'Hello world!' echo ${myArray[@]@Q}
'48' '65' '6C' '6C' '6F' '20' '77' '6F' '72' '6C' '64' '21'
Note: as function use ${*:2} as source string, space don't need to be quoted:
ascii2hex myArray Hello world! echo ${myArray[@]@Q}
'48' '65' '6C' '6C' '6F' '20' '77' '6F' '72' '6C' '64' '21'
2. Hexadecimal to Ascii conversion in bash
Simply:
printf '%b' ${myArray[@]/#/\\x}
Hello world!
2.1. Then into a variable:
printf -v string '%b' ${myArray[@]/#/\\x} echo $string
Hello world!
2.2. Into a function to define a variable
hex2ascii() { local _array=(${*:2}) printf -v "$1" '%b' ${_array[@]/#/\\x} } hex2ascii mystring ${myArray[@]} echo "$mystring"
Hello world!