Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'd like to convert ASCII code (like - or _ or ., etc.) to hexadecimal representation in the Unix shell (without bc command), eg : - => %2d.

Any ideas?

share|improve this question
See my answer to this question which you cross-posted on Stack Overflow. – Dennis Williamson Aug 27 '10 at 23:53

There's a printf tool that simulates the C function; normally it's at /usr/bin/printf, but a lot of shells implement built-ins for it as well. You can use %02x to get the hex representation of a character, but you need to make sure you pass a string that includes the character in single-quotes (Edit: It turns out just a single-quote at the beginning is sufficient):

printf "%%%02x\n" "'-"   # Outputs %2d

You can make a shell function for convenience:

function hex() {
    printf "%%%02x\n" "'$1"

hex -   # Outputs %2d
hex _   # Outputs %5f
hex .   # Outputs %2e
share|improve this answer
thx a lot, it works perfectly – Olivier DUVAL Aug 30 '10 at 12:32

Try od:

$ echo -n "-_." | od -A n -t x1

2d 5f 2e

-A n means do not print offsets and -t x1 means that the type of the input is hexadecimal integers of 1 byte.

share|improve this answer
Nice. You can use echo -n to omit the newline at the end so od doesn't pick it up and turn it into 0a – Michael Mrozek Aug 27 '10 at 17:07

xxd is a hex-dump utility shipped as part of the vim-common package
It has a handy -p option which outputs a continuous 'plain/postscript' hexdump style.. This can eaisly be reversed via -r... -u will output upper-case Hex-Digits.

$ echo -n "M" |xxd -p    # 1 ASCII char= 1 UTF-8 byte; Unicode Codepoint: U+0041

$ echo -n "〶" |xxd -p -u # 1 CJK char= 3 UTF-8 bytes; Unicode Codepoint: U+3036  

$ echo -n "Dump a string" |xxd -p -u  

$ echo -n "Dump and Revert" |xxd -p |xxd -r  
Dump and Revert
share|improve this answer
Perhaps add -p switch when reverting: xxd -r -p. Just xxd -r didn't work for me in the example above. – bytefire Jan 28 at 11:31

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.