November 28, 2010
I'm busy converting a project of mine from PHP in to Ruby, and one of the things it needs to be able to do is convert a bunch of hex characters into a string (and vice versa)... which I wasn't sure how to do, so I hit Google. As it turns out there seem to be several other people who've needed to do the same thing, without finding the answer they were looking for, so I got to trying to code my own functions and managed to come up with this:
# hex_to_string("486578546f537472") returns "HexToStr"
def hex_to_string(str)
returned = ''
for i in (0..str.length).step(2)
unless str[i].nil?
hex_chr = str[i].chr + str[i+1].chr
returned += hex_chr.hex.chr
end
end
returned
end
# string_to_hex("StrToHex") returns "537472546f486578"
def string_to_hex(str)
returned = ''
for i in (0..str.length)
unless str[i].nil?
returned += str[i].to_s(16)
end
end
returned
end
I'm still new to Ruby, and don't really know what I'm doing, so please feel free to make any improvements or suggestions. You can find the latest versions of these functions on github: https://github.com/hypn/HexToString