10

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?

1

3 Answers 3

15

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
1
  • The only issue with this is with 2-byte characters whose code starts with 0. eg hex 'ץ' will give %5e5 rather than %05e5. You should change the body of the function to s=printf "%%%04x" "'$1"; echo "%${s%00}"
    – pyrocrasty
    Jan 22, 2020 at 6:26
6

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 easily 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
1
  • Perhaps add -p switch when reverting: xxd -r -p. Just xxd -r didn't work for me in the example above.
    – bytefire
    Jan 28, 2016 at 11:31
5

Try od:

$ echo -n "-_." | od -A n -t x1
2d 5f 2e

-A n means do not print offsets and -t x1 means format output as 1 byte hexadecimal integer.

1
  • 2
    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 Aug 27, 2010 at 17:07

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .