Dan
Dan

Reputation: 1183

Binary of charcodes to legible string?

I'm confused about binaries and strings in Elixir. I have a function. That returns a binary of character codes that represents a string, but I can't figure out how to print that string in a legible way. I was thinking of converting the binary to a character list then enumerating the character list and converting each char to a string, but that seems like a lot of work. Is there a better way?

Upvotes: 3

Views: 7544

Answers (1)

Brandon
Brandon

Reputation: 6872

Try String.chunk/2

iex(1)> a = "Hello " <> <<0>> <> "World"
<<72, 101, 108, 108, 111, 32, 0, 87, 111, 114, 108, 100>>
iex(2)> String.chunk(a, :printable)     
["Hello ", <<0>>, "World"]

Upvotes: 10

Related Questions