13

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"
2

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

5 Comments

i get => "\000\016\000\000\000\000\000" for your solution I am running 1.8.7 ruby
@Pavan: Which is correct, seeing that "\000\016" == "\x00\x0e"
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: That's a formatting issue. What you want then is a string like "\\x00\\x0e...". Lemme hack that up really quick.
@Pavan: Check my edit. Also, I edited your question to reflect your additional problem.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.