Convert string to hexadecimal in Ruby
Ruby 1.9 added an even easier way to do this:
"0x101".hex
will return the number given in hexadecimal in the string.
Change this line:
line = a.map { |b| ", #{b}" }.join
to this:
line = a.map { |b| sprintf(", 0x%02X",b) }.join
(Change to %02x
if necessary, it's unclear from the example whether the hex digits should be capitalized.)
I don't know if this is the best solution, but this a solution:
class String
def to_hex
"0x" + self.to_i.to_s(16)
end
end
"116".to_hex
=> "0x74"