如何将UCS2字符串转换为UTF8?
如何将UCS2中的字符串(每个字符2个字节)转换为Ruby中的UTF8字符串?
您应该查看iconv ,它是Ruby标准库的一部分。 它专为此任务而设计。
特别,
Iconv.iconv("utf-8", "utf-16", str).first
应该处理转换。
因为大多数情况下字符串在UCS2编码中的字符串可以表示为UTF-16字符串(在代码大于0x10000的UTF-16字符中很少使用)我认为使用Iconv是转换字符串的更好方法。 示例代码:
require 'iconv' ic = Iconv.new 'UTF-8', 'UTF-16' utf8string = ic.iconv ucs2string
使用Ruby 1.9:
string.encode("utf-8")
如果字符串编码未知,您可能需要先设置它:
string.force_encoding("utf-16be").encode("utf-8") # Big-endian string.force_encoding("utf-16le").encode("utf-8") # Little-endian