Robert Mark Bram
Robert Mark Bram

Reputation: 9663

Convert string to encoded hex

Not too sure about the operations going on here, but when I go to http://codebeautify.org/string-hex-converter and enter 1yS9$dNc, I see output: 3179533924644e63.

In bash I do:

printf "1yS9$dNc" | xxd
0000000: 3179 5339                                1yS9

From the man page, I get that xxd creates a hex dump of a given file or standard input.

My question:

  1. Can I use Bash to get the same output from codebeautify (i.e. go from 1yS9$dNc to 3179533924644e63).
  2. How is codebeautify encoding this differently?

Upvotes: 1

Views: 505

Answers (1)

John1024
John1024

Reputation: 113814

You need to use single quotes. Compare:

$ printf "1yS9$dNc" | xxd
0000000: 3179 5339                                1yS9

With:

$ printf '1yS9$dNc' | xxd
0000000: 3179 5339 2464 4e63                      1yS9$dNc

The reason that your xxd output was short was that the shell expanded the value of $dNc to an empty string. So, the only characters that xxd saw were 1yS9. If you use single-quotes, by contrast, the shell expands nothing.

Inside double quotes, the shell performs (1) variable expansion, (2) command substitution, (3) arithmetic expansion. If you want those, use double-quotes, If you don't use single-quotes.

Formatting options

To make the output look a little bit more like codebeautify, use -g 0:

$ printf '1yS9$dNc' | xxd -g 0
0000000: 3179533924644e63                  1yS9$dNc

Or, better yet, use -plain:

$ printf '1yS9$dNc' | xxd -plain
3179533924644e63

Saving the result in a variable

If the goal is to get the hex value into a shell variable, then, with bash:

$ printf -v var "%s" $(xxd -p <<<'1yS9$dNc')
$ echo $var
3179533924644e630a

Hat tip: David C. Rankin

Upvotes: 2

Related Questions