Reputation:
How can I convert "1234567890"
to "\x12\x34\x56\x78\x90"
in Ruby?
Upvotes: 18
Views: 18806
Reputation: 14798
Assuming you have a well-formed hexadecimal string (pairs of hex digits), you can pack to binary, or unpack to hex, simply & efficiently, like this:
string = '0123456789ABCDEF'
binary = [string].pack('H*') # case-insensitive
=> "\x01#Eg\x89\xAB\xCD\xEF"
hex = binary.unpack('H*').first # emits lowercase
=> "012345679abcdef"
Upvotes: 8
Reputation: 11289
Ruby 1.8 -
hex_string.to_a.pack('H*')
Ruby 1.9 / Ruby 1.8 -
Array(hex_string).pack('H*')
Upvotes: 13
Reputation: 7297
(0..4).map { |x| "0x%X" % (("1234567890".to_i(16) >> 8 * x) & 255) }.reverse
Upvotes: -1
Reputation: 49
class String
def hex2bin
s = self
raise "Not a valid hex string" unless(s =~ /^[\da-fA-F]+$/)
s = '0' + s if((s.length & 1) != 0)
s.scan(/../).map{ |b| b.to_i(16) }.pack('C*')
end
def bin2hex
self.unpack('C*').map{ |b| "%02X" % b }.join('')
end
end
Upvotes: 4
Reputation: 237060
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}")}
Upvotes: 1