hexadecimal dump to binary - xxd -r equivalent
Asked Answered
D

1

1

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 ?

Devout answered 15/2, 2017 at 23:26 Comment(0)
G
5

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.
Grossman answered 15/2, 2017 at 23:40 Comment(1)
or [my_hex_string].pack('H*')Polypary

© 2022 - 2024 — McMap. All rights reserved.