How To Convert An Elixir Binary To A String?

前端 未结 6 1566
天命终不由人
天命终不由人 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 03:03

    There's a couple of things here:

    1.) You have a list with a tuple containing one element, a binary. You can probably just extract the binary and have your string. Passing the current data structure to to_string is not going to work.

    2.) The binary you used in your example contains 0, an unprintable character. In the shell, this will not be printed properly as a string, due to the fact that Elixir can't tell the difference between just a binary, and a binary representing a string, when the binary representing a string contains unprintable characters.

    3.) You can use pattern matching to convert a binary to a particular type. For instance:

    iex> raw = <<71,32,69,32,84,32>>
    ...> Enum.join(for <>, do: <>)
    "G E T "
    ...> <> = raw
    "G"
    

    Also, if you are getting binary data from a network connection, you probably want to use :erlang.iolist_to_binary, since the data will be an iolist, not a charlist. The difference is that iolists can contain binaries, nested lists, as well as just be a list of integers. Charlists are always just a flat list of integers. If you call to_string, on an iolist, it will fail.

提交回复
热议问题