17

I've found many posts on StackOverflow which have covered this question in C++, C# and other languages, but none with Shell.

Using Bash/Shell, how do I convert a random String into a byte array?

I tried:

echo "some string" | xxd -r -p 

but it didn't work.

I basically want a byte output - e.g. )?e?GV??vY?Ge?#G

3
  • 1
    A byte array with what encoding? Commented Dec 3, 2015 at 21:21
  • 2
    Byte output of "some string" is "some string". Commented Dec 3, 2015 at 21:51
  • 1
    @alecrosic : How does the example output you provided, relate to the input? Commented Nov 23, 2020 at 14:11

2 Answers 2

33

If you want to get the hex values of some string, then this works:

$ echo "testing some values"$'\157' | xxd 0000000: 7465 7374 696e 6720 736f 6d65 2076 616c testing some val 0000010: 7565 736f 0a ueso. 

If you just need the "plain" string:

$ echo "testing some values"$'\157' | xxd -p 74657374696e6720736f6d652076616c7565736f0a 

If you need to "reverse" an hex string, you do:

$ echo "74657374696e6720736f6d652076616c7565736f0a" | xxd -r -p testing some valueso 

If what you need is the character representation (not hex), you could do:

$ echo "testing:"$'\001\011\n\bend test' | od -vAn -tcx1 t e s t i n g : 001 \t \n \b e n d 74 65 73 74 69 6e 67 3a 01 09 0a 08 65 6e 64 20 t e s t \n 74 65 73 74 0a 

Or:

$ echo "testing:"$'\001\011\n\bend test' | od -vAn -tax1 t e s t i n g : soh ht nl bs e n d sp 74 65 73 74 69 6e 67 3a 01 09 0a 08 65 6e 64 20 t e s t nl 74 65 73 74 0a 
Sign up to request clarification or add additional context in comments.

2 Comments

Can I ask why did you add "o" at the end ($'\157')? I thought these are some flags to this command and spent like 2 hours trying to figure out where is this extra "o" comming from.
Thank you for your answer regardless. It was very helpful.
0

Looks like you want to convert hex string to bytes. xxd needs a starting point (since it is used to patch binary files and such)

string="626c610a" echo "0: $string" | xxd -r 

xxd will also silently skip any invalid hex, so check your data if you get empty output.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.