If your system has a rev
command.
hex=030201
new_hex=$(printf %s "$hex" | dd conv=swab 2> /dev/null | rev)
If it has a tac
or tail -r
command:
new_hex=$(echo "$hex" | fold -w 2 | tac | paste -sd '\0' -)
With zsh
:
setopt extendedglob
new_hex=${(j[])${(s[]Oa)${hex//(#b)(?)(?)/$match[2]$match[1]}}}
(like in the dd
approach: swap pairs of characters, split into list of individual characters (s[]
), reverse the order (Oa
) and join (j[]
)).
Or:
printf -v new_hex '%2$s%1$s' ${(s[]Oa)hex}
POSIXly:
new_hex=$(
awk '
BEGIN {
hex = ARGV[1]; l = length(hex)
for (i = 1; i < l; i += 2)
new_hex = substr(hex, i, 2) new_hex
print new_hex
}' "$hex"
)
Or
new_hex=$(echo "$hex" |
sed -e 'G;:1' -e 's/\(..\)\(.*\n\)/\2\1/;t1' -e 's/.//')
With perl
:
new_hex=$(perl -le 'print reverse(shift =~ /../g)' -- "$hex")
010203
as an hexadecimal, even though I do not use0x