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”

  1. David Lowenfels Says:

    Here's a cleaner version:

    
      def hex_string_to_ascii hex_str
        returning ascii_str = '' do
          hex_str.split('').in_groups_of(2){|c| ascii_str << (c[0]+c[1]).hex.chr }
        end
      end
    
    

    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?

  2. David Lowenfels Says:

    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 {...}

  3. Nicolás Sanguinetti Says:

    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
      end
    
  4. David Lowenfels Says:

    Here's a even more svelte method:

    str = "0#{str}" if str.size.odd?
    str.scan(/../).map { |pair| pair.hex.chr }.join

  5. Meekish Says:

    How about going the other direction (ASCII -> Hex)?

Sorry, comments are closed for this article.