Reputation: 11
I want to translate a string in hex to utf-8, for example,"\\XB6\\XAB..."
to "中国"
. I use "\x68\x65\x6c\x6c\x6f".unpack("Z*")
→ "hello"
but it doesn't work.
Upvotes: 1
Views: 3309
Reputation: 11
Make sure you use double quotes to define your string, otherwise you will not get the result you expect.
Example using double quotes:
"\xe4\xb8\xad\xe5\x9b\xbd".force_encoding("UTF-8") => "中国"
Example using single quotes:
'\xe4\xb8\xad\xe5\x9b\xbd'.force_encoding("UTF-8") => "\\xe4\\xb8\\xad\\xe5\\x9b\\xbd"
Upvotes: 1
Reputation: 179717
If you're using Ruby 1.9, use String#force_encoding
:
"\xe4\xb8\xad\xe5\x9b\xbd".force_encoding("UTF-8")
Upvotes: 2