Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string with hex ASCII codes to characters

Tags:

ruby

ascii

I have a string containing hex code values of ASCII characters, e.g. "666f6f626172". I want to convert it to the corresponding string ("foobar").

This is working but ugly:

"666f6f626172".scan(/../).map(&:hex).map(&:chr).join # => "foobar" 

Is there a better (more concise) way? Could unpack be helpful somehow?

like image 358
undur_gongor Avatar asked Apr 09 '14 09:04

undur_gongor


People also ask

Which function is used to convert hexadecimal values to the ascii characters *?

sprintf() will convert your presumably binary data to an ASCII hex string or a decimal hex string.


2 Answers

You can use Array#pack:

["666f6f626172"].pack('H*') #=> "foobar" 

H is the directive for a hex string (high nibble first).

like image 196
Stefan Avatar answered Sep 22 '22 01:09

Stefan


Stefan has nailed it, but here's an alternative you may want to tuck away for another time and place:

"666f6f626172".gsub(/../) { |pair| pair.hex.chr } # => "foobar" 
like image 36
Cary Swoveland Avatar answered Sep 21 '22 01:09

Cary Swoveland