Reputation: 39
I have an HEX string, and I what to convert each character in it to DEC, and to output them with space separated and in brackets. see example:
input: "A1B2C3D4"
output: "[10 1 11 2 12 3 13 4 ]"
Upvotes: 0
Views: 103
Reputation: 195029
this awk one-liner does the job:
awk -v FS='' --non-decimal-data '{for(i=1;i<=NF;i++)printf "%d%s","0x"$i,(i==NF?RS:" ")}'
test with your example:
kent$ echo "A1B2C3D4"|awk -v FS='' --non-decimal-data '{for(i=1;i<=NF;i++)printf "%d%s","0x"$i,(i==NF?RS:" ")}'
10 1 11 2 12 3 13 4
here two things need to pay attention :
--non-decimal-data
option for gawk to recognize hex input0x
to each hex digit.an alternative with build-in printf
:
awk -v FS='' '{for(i=1;i<=NF;i++){"printf \"%d\" \"0x"$i"\""|getline v;printf "%d%s",v,(i==NF?RS:" ")}}'
test:
kent$ echo "A1B2C3D4"|awk -v FS='' '{for(i=1;i<=NF;i++){"printf \"%d\" \"0x"$i"\""|getline v;printf "%d%s",v,(i==NF?RS:" ")}}'
10 1 11 2 12 3 13 4
Upvotes: 2