Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decode hexadecimal string in Ruby [duplicate]

Tags:

ruby

Possible Duplicate:
Hex to binary in ruby

In Python, I can do the following:

>>> str = '000E0000000000'
>>> str.decode('hex')
'\x00\x0e\x00\x00\x00\x00\x00'

If I have to achieve the same output in ruby which call could I make? I tried to_s(16), which doesn't seem to work. I need the output to be in that specific format, so I expect to get the following:

"\\x00\\x0e\\x00\\x00\\x00\\x00\\x00"
like image 278
Pavan K Avatar asked Mar 30 '12 13:03

Pavan K


1 Answers

irb(main):002:0> [str].pack('H*')
# => "\x00\x0E\x00\x00\x00\x00\x00"

Or (Ruby 1.9 only):

irb(main):004:0> str.scan(/../).map(&:hex).map(&:chr).join
# => "\x00\x0E\x00\x00\x00\x00\x00"

If you need the string formatted:

irb(main):005:0> s = str.scan(/../).map { |c| "\\x%02x" % c.hex }.join
=> "\\x00\\x0e\\x00\\x00\\x00\\x00\\x00"
irb(main):006:0> puts s
\x00\x0e\x00\x00\x00\x00\x00
=> nil
like image 125
Niklas B. Avatar answered Nov 04 '22 04:11

Niklas B.