How To Convert An Elixir Binary To A String?

前端 未结 6 1554
天命终不由人
天命终不由人 2020-12-10 02:41

So I\'m trying to convert a binary to a string. This code:

t = [{<<71,0,69,0,84,0>>}]
String.from_char_list(t)

But I\'m gettin

6条回答
  •  自闭症患者
    2020-12-10 02:58

    Not sure if OP has since solved his problem, but in relation to his remark about his binary being utf16-le: for specifically that encoding, I found that the quickest (and to those more experienced with Elixir, probably-hacky) way was to use Enum.reduce:

    # coercing it into utf8 gives us ["D", <<0>>, "e", <<0>>, "v", <<0>>, "a", <<0>>, "s", <<0>>, "t", <<0>>, "a", <<0>>, "t", <<0>>, "o", <<0>>, "r", <<0>>]
    <<68, 0, 101, 0, 118, 0, 97, 0, 115, 0, 116, 0, 97, 0, 116, 0, 111, 0, 114, 0>>  
    |> String.codepoints()
    |> Enum.reduce("", fn(codepoint, result) ->
                         << parsed :: 8>> = codepoint
                         if parsed == 0, do: result, else: result <> <>
                       end)
    
    # "Devastator"
    |> IO.puts()
    

    Assumptions:

    • utf16-le encoding

    • the codepoints are backwards-compatible with utf8 i.e. they use only 1 byte

    Since I'm still learning Elixir, it took me a while to get to this solution. I looked into other libraries people made, even using something like iconv at a bash level.

提交回复
热议问题