How do I convert a UCS2 string into UTF8?

前端 未结 3 370
野趣味
野趣味 2021-01-14 14:48

How to convert a string that is in UCS2 (2 bytes per character) into a UTF8 string in Ruby?

3条回答
  •  难免孤独
    2021-01-14 15:42

    With Ruby 1.9:

    string.encode("utf-8")
    

    If the string encoding is not known, you may need to set it first:

    string.force_encoding("utf-16be").encode("utf-8") # Big-endian
    string.force_encoding("utf-16le").encode("utf-8") # Little-endian
    

提交回复
热议问题