views:

1033

answers:

4

Lets say that I have a string "5a". This is the hex representation of the ASCII letter 'Z'. I need to know a linux shell command which will take a hex string and output the binary bytes the string represents.

So if I do echo "5a" | command_im_looking_for > temp.txt

can I open temp.txt, I will see a solitary letter Z.

+3  A: 
echo -n 5a | perl -pe 's/([0-9a-f]{2})/chr hex $1/gie'

Note that this won't skip non-hex characters. If you want just the hex (no whitespace from the original string etc):

echo 5a | perl -ne 's/([0-9a-f]{2})/print chr hex $1/gie'

Also, zsh and bash support this natively in echo:

echo -e '\x5a'
bdonlan
You probably need to put an "i" after the regexes there.
Kinopiko
Whoops, thanks :)
bdonlan
Or put a-fA-F in the character class.
Kinopiko
I'm not normally a fan of perl, but this is the sort of stuff that it does well. If you're going to be converting a very large amount of data, though, it would be better to write a short C program to do this.
Adam Rosenfield
I don't think you will see much benefit from doing it in C until you have to deal with terabytes of data.
Kinopiko
@Kinopiko, it processes about 1.5 MB/s (output) here, so really, by the time you get to hundreds of megabytes, it's time to write something in a faster language :)
bdonlan
Much easier to use `perl -lne 'print pack "H*", $_'`.
Randal Schwartz
@Randal, it's easier for me to use this one because I don't need to `perldoc -f pack` each time ;) of course, YMMV...
bdonlan
A: 
echo 5a | python -c "import sys; print chr(int(sys.stdin.read(),base=16))"
unutbu
+2  A: 

od -c or hexdump -c

james
No, that converts in the other direction (chars to octal or hex).
Dennis Williamson
Check the syntax. The -c gives character output. -a gives ascii only. I typically use it to view an unknown file e.g. "od -c filename | more" and it dumps out the file with readable characters
james
A: 

depending on where you got that "5a', you can just append \x to it and pass to printf

$ a=5a
$ a="\x${a}"
$ printf "$a"
Z
ghostdog74
The second and third lines can be collapsed into one: `printf "\x${a}"`
Dennis Williamson