user3748817
user3748817

Reputation: 39

Convert hex string to decimal char by char

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

Answers (1)

Kent
Kent

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 input
  • add a leading 0x to each hex digit.

EDIT

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

Related Questions