tags:

views:

548

answers:

4

How can I convert "1234567890" to {0x12, 0x34, 0x56, 0x78, 0x90} in Ruby?

A: 

(0..4).map { |x| "0x%X" % (("1234567890".to_i(16) >> 8 * x) & 255) }.reverse

Kevin Peterson
A: 

You might find it helpful to take a look here at this post

Izabela
+1  A: 

If you have a string containing numbers and you want to scan each as a numeric hex byte, I think this is what you want:

"1234567890".scan(/\d\d/).map {|num| Integer("0x#{num}")}
Chuck
I'd have done: "1234567890".scan(/\d\d/).map {|i| i.to_i(16) }
Greg
+1  A: 

Code -

hex_string.to_a.pack('H*')
Vikrant Chaudhary
File.open('output.txt', 'w+') {|f| f.write(IO.read('input.txt').to_a.pack('H*')) }
neoneye