user3206440
user3206440

Reputation: 5059

hexadecimal dump to binary - xxd -r equivalent

In Linux bash shell, I use the following to convert a plain hexadecimal dump into binary

$ echo "8cd59ef53c9aaa68311b73767e0975e7" | xxd -r -p > xxd_out.bin

when I open the file in text viewer it looks like ŒÕžõ<šªh1sv~ uç

or in xxd

$ xxd -b xxd_out.bin
00000000: 10001100 11010101 10011110 11110101 00111100 10011010  ....<.
00000006: 10101010 01101000 00110001 00011011 01110011 01110110  .h1.sv
0000000c: 01111110 00001001 01110101 11100111                    ~.u.

or in Notepad++ Hex-Editor (plugin) view enter image description here

How can I get the same binary output in Ruby ? Is there any library available which does what xxd -r -p would do ?

Upvotes: 1

Views: 4321

Answers (1)

ymonad
ymonad

Reputation: 12100

use Array#pack

.scan(/../) will split "8cd59e" into ["8c","d5","9e"]

.map(&:hex) will convert it to [0x8c, 0xd5, 0x9e]

.pack("c*") will pack it to "\x8c\xd5\x9e"

echo "8cd59ef53c9aaa68311b73767e0975e7" | \
  ruby -ne 'print $_.scan(/../).map(&:hex).pack("c*")' | \
  xxd -b

output:

00000000: 10001100 11010101 10011110 11110101 00111100 10011010  ....<.
00000006: 10101010 01101000 00110001 00011011 01110011 01110110  .h1.sv
0000000c: 01111110 00001001 01110101 11100111                    ~.u.

Upvotes: 5

Related Questions