hexadecimal dump to binary - xxd -r equivalent

╄→гoц情女王★ 提交于 2019-12-11 05:07:14

问题


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

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


回答1:


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.


来源:https://stackoverflow.com/questions/42262046/hexadecimal-dump-to-binary-xxd-r-equivalent

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!