Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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
3  
See my answer to this question which you cross-posted on Stack Overflow. –  Dennis Williamson Aug 27 '10 at 23:53
add comment

3 Answers

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
4d

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

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

$ echo -n "Dump and Revert" |xxd -p |xxd -r  
Dump and Revert
share|improve this answer
add comment

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
1  
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
add comment

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
add comment

Your Answer

 
discard

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.