的 发
的 发

Reputation: 11

How to translate hex to utf-8

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

Answers (2)

briancase
briancase

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

nneonneo
nneonneo

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

Related Questions