Ruby 一个 utf-16 的 byte array 怎么转换成 string?

aikko · June 25, 2013 · Last by aikko replied at June 26, 2013 · 4466 hits

从一个 base64 编码的 string,通过.unpack("m*") 获得的是一个 utf-16 的 byte array,如何转成相对应的 string

byte_array.force_encoding('utf-16le').encode 'utf-8'

如果 le 不对就换成 'utf-16be'

#1 楼 @luikore undefined method `force_encoding' for #Array:0x2584830 这样不行,我最后通过把这个 byte array 写到一个文件里面再读出来。

f = File.open("tmp.txt", "wb") do |output| result.each do | byte | output.print byte.chr end end

fd = File.open("tmp.txt", "rb:UTF-16LE") while line = fd.gets line = line.encode("UTF-8") puts line end

其中 result 即我获得的 byte_array

#1 楼 不知是否有其他办法~请教 @robbin @luikore

[15] pry(main)> str = "xyz yzx zxy".encode("UTF-16LE")
=> "xyz yzx zxy"
[16] pry(main)> str.encoding
=> #<Encoding:UTF-16LE>
[17] pry(main)> require "base64"
=> false
[18] pry(main)> Base64.urlsafe_encode64(str)
=> "eAB5AHoAIAB5AHoAeAAgAHoAeAB5AA=="
[19] pry(main)> base64_str = _
=> "eAB5AHoAIAB5AHoAeAAgAHoAeAB5AA=="
[20] pry(main)> base64_str.unpack("m*")
=> ["x\x00y\x00z\x00 \x00y\x00z\x00x\x00 \x00z\x00x\x00y\x00"]
[21] pry(main)> base64_str.unpack("m*").first.force_encoding("UTF-16LE").encode("UTF-8")
=> "xyz yzx zxy"

#4 楼 @Saito 多谢,测试可行,但中文会乱码

You need to Sign in before reply, if you don't have an account, please Sign up first.