Quick fix: string to hex conversion in bash
Just the other day a had to do some simple string to hex conversion without
having any other tool available. Thanks to bash’s arithmetic features, it’s
easy to implement; just the lack of a strindex()
function made it harder
than it needs to be, but over there at
stackoverflow I found inspirations.
Usage:
$ s2h foobar
666F6F626172
$ h2s 666F6F626172
foobar
Check against working tool:
$ echo -n "foobar" | hd
00000000 66 6f 6f 62 61 72 |foobar|
00000006
Full code:
trindex() {
X="${1%%$2*}"
[[ "$X" = "$1" ]] && echo -1 || echo "$[ ${#X} ]"
}
function s2h () {
a=$1
out=""
for ((i=0;i<${#a};i++)); do
tmp=$(printf %02X \'${a:$i:1})
out=${out}${tmp}
done
echo $out
}
# echo -e "\x48"
function h2s () {
a=$1
out=""
for ((i=0;i<${#a};i=i++)); do
tchar="\x${a:$i:2}"
out=${out}$(echo -ne $tchar)
i=$((i+2))
done
echo $out
}