I am doing some work with encryption keys and was trying to find a method in ruby that would convert a string of hex values into their ascii equivalent. I am storing the keys in my database as a string. Here is a sample key that I am using:
"4bd3eb6bd171595764ec2050a20382e1"
which is represented in a hex array as:
0x4b, 0xd3, 0xeb, 0x6b, 0xd1, 0x71, 0x59, 0x57, 0x64, 0xec, 0x20, 0x50, 0xa2, 0x03, 0x82, 0xe1
I iterate through my array, 2 characters at a time, thanks to the rails enumerable "ingroupsof". I take the string of two hex values and convert it to their ascii equivalent first by converting the text into hex and then asking for the char equivalent in ascii. I stuff this back into a new string and voila!... I've got my ascii string.
def hex_string_to_ascii str
new_str = ''
arr = str.split('')
arr.in_groups_of(2){|c| new_str << ("#{c[0]}#{c[1]}".hex.chr) }
new_str
end
5 Responses to “Converting a hex string to ascii in rails”
Sorry, comments are closed for this article.


April 18th, 2007 at 06:56 AM
Here's a cleaner version:
it could also be nice to do some error checking, e.g.:
hex_str.gsub(/[^A-Fa-f\d]/,'')
hexstr = '0'+hexstr if hex_str.size.odd?
April 20th, 2007 at 07:06 PM
Thanks to "Caleb":http://ruby.meetup.com/6/members/2599323/ for suggesting the String#scan method:
hex_str.split('').in_groups_of(2) {...}becomes
hex_str.scan(/../).each {...}April 21st, 2007 at 05:01 PM
I'd clean David's version a little more:
def hex_string_to_ascii(hex_str) returning '' do |ascii_str| hex_str.scan(/../).each {...} end endApril 22nd, 2007 at 09:50 PM
Here's a even more svelte method:
str = "0#{str}" if str.size.odd?str.scan(/../).map { |pair| pair.hex.chr }.join
June 17th, 2007 at 06:03 PM
How about going the other direction (ASCII -> Hex)?