12

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"
Community
  • 1
  • 1
Pavan K
  • 4,085
  • 8
  • 41
  • 72
  • Perhaps this is the solution? [http://stackoverflow.com/questions/84421/converting-an-integer-to-a-hexadecimal-string-in-ruby][1] [1]: http://stackoverflow.com/questions/84421/converting-an-integer-to-a-hexadecimal-string-in-ruby – René Höhle Mar 30 '12 at 13:37
  • [str].pack('H*') => "\000\016\000\000\000\000\000" – Pavan K Mar 30 '12 at 13:43

1 Answers1

13
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
Niklas B.
  • 92,950
  • 18
  • 194
  • 224
  • i get => "\000\016\000\000\000\000\000" for your solution I am running 1.8.7 ruby – Pavan K Mar 30 '12 at 13:47
  • @Pavan: Which is correct, seeing that `"\000\016" == "\x00\x0e"` – Niklas B. Mar 30 '12 at 13:47
  • trouble is I need to get the \x00 format and not \000 format as the url receiver is complaining of invalid format whereas the python decode prints \x00 format and the url receiver doesn't complain for that – Pavan K Mar 30 '12 at 13:49
  • @Pavan: That's a formatting issue. What you want then is a string like `"\\x00\\x0e..."`. Lemme hack that up really quick. – Niklas B. Mar 30 '12 at 13:51
  • @Pavan: Check my edit. Also, I edited your question to reflect your additional problem. – Niklas B. Mar 30 '12 at 13:54