将UTF-16LE Elixir位串转换为Elixir字符串



给定一个用UTF-16LE编码的Elixir位串:

<<68, 0, 101, 0, 118, 0, 97, 0, 115, 0, 116, 0, 97, 0, 116, 0, 111, 0, 114, 0, 0, 0>>

如何将其转换为可读的Elixir字符串(它拼出"Devastator")?我得到的最接近的是将上面的代码转换为Unicode代码点(["0044", "0065", ...])的列表,并尝试将u转义序列添加到它们之前,但Elixir抛出错误,因为它是无效序列。我没主意了。

最简单的方法是使用:unicode模块中的函数:

:unicode.characters_to_binary(utf16binary, {:utf16, :little})
例如

<<68, 0, 101, 0, 118, 0, 97, 0, 115, 0, 116, 0, 97, 0, 116, 0, 111, 0, 114, 0, 0, 0>>
|> :unicode.characters_to_binary({:utf16, :little})
|> IO.puts
#=> Devastator

(在最后有一个空字节,所以在shell中将使用二进制显示而不是字符串,并且根据操作系统,它可能会为空字节打印一些额外的表示)

您可以使用Elixir的模式匹配,特别是<<codepoint::utf16-little>>:

defmodule Convert do
  def utf16le_to_utf8(binary), do: utf16le_to_utf8(binary, "")
  defp utf16le_to_utf8(<<codepoint::utf16-little, rest::binary>>, acc) do
    utf16le_to_utf8(rest, <<acc::binary, codepoint::utf8>>)
  end
  defp utf16le_to_utf8("", acc), do: acc
end
<<68, 0, 101, 0, 118, 0, 97, 0, 115, 0, 116, 0, 97, 0, 116, 0, 111, 0, 114, 0, 0, 0>>
|> Convert.utf16le_to_utf8
|> IO.puts
<<192, 3, 114, 0, 178, 0>>
|> Convert.utf16le_to_utf8
|> IO.puts
输出:

Devastator
πr²

最新更新