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"
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With