Friday, June 24, 2005

Linux Hexadecimal HOWTO


There are 4 things you need to do with HEX values in LINUX


For the impatient:

1) Convert Hex to Decimal
  • echo 68 65 6c 6c 6f 20 77 6f 72 6c 64 |tr '[a-z]' '[A-z]' |sed 's/ / p /g' |sed 's/$/ p/'|awk '{print "16i "$0}'|dc |tr '\n' ' '
104 101 108 108 111 32 119 111 114 108 100

4) Convert Hex to ASCII

  • echo 68656c6c6f20776f726c64 |sed 's/../& /g' |tr '[a-z]' '[A-z]' |sed 's/ / p /g' |sed 's/$/ p/'|awk '{print "16i "$0}'|dc |tr ' ' '\n' |awk '{printf("%c",$0)}'
  • Even Better -
  • echo 68656c6c6f20776f726c64 | xxd -r -p
hello world

2)Convert Decimal to Hex
  • echo 87 87|tr ' ' '\n'|awk '{printf "%x ",$1}'
57 57
3) Convert ASCII to HEX
  • echo -n hello world |od -tx1 |cut -c8-|tr -d ' \n'
68656c6c6f20776f726c64

More Examples:

If it wasn't so simple, you could put it in a script and call it ascii2hex.sh.

This command is usefull to encode ascii text into 8 bit Hex (UCS2)
for sending the payload of a PDU sms message.

If it wasn't so simple, you could put it in a script and call it ascii2hex.sh.

echo -n "202.9.98.54:8080/CGServer/serve.jsp?id=123456" |od -tx1
0000000 32 30 32 2e 39 2e 39 38 2e 35 34 3a 38 30 38 30
0000020 2f 43 47 53 65 72 76 65 72 2f 73 65 72 76 65 2e
0000040 6a 73 70 3f 69 64 3d 31 32 33 34 35 36
0000055


Just ignore the first column or cut it out and remove the non-text characters with "| cut -c 8- |tr -d ' \n' "
3230322e392e39382e35343a383038302f43475365727665722f73657276652e6a73703f69643d313233343536

Here is a standard 8 bit ascii chart to verify the results.

x="C0 AA BB CC"

echo "16i C0 p AA p BB p CC p" | dc
192
170
187
204


OR

echo -e "16i\t$x"|sed 's/ / p /g' |sed 's/$/ p/'|dc
192
170
187
204

_____________

Single number conversion


Hex to Integer
echo 16i 57 p |dc
87

Integer to Hex
echo 87 16 o p |dc

57

5 comments:

Anonymous said...

Great post, i'm bookmarking :)

Anonymous said...

Thanks. Even 4 years later it is still of use.

In the case of Hex to ASCII I would remove the following from the command chain though:

|sed 's/$/ p/'

This causes 2 times "p" at the end of the HEX string. So you get the last ASCII character twice.

Dharma said...

Thanks so much.. I love the "echo 68656c6c6f20776f726c64 | xxd -r -p" method..

It helped a lot.

Dharma said...

Thanks so much.. I love the "echo 68656c6c6f20776f726c64 | xxd -r -p" method..

It helped a lot.

Anonymous said...

Just want to tell you thank you, i have searched the web and your solution was far the best!