0

Consider this variable

X = "1_2_3_4",

How to I get X into a binary string format?

So like this

<<"1_2_3_4">>

I'm getting all manner of errors trying to figure it out.

Thanks in advance, Snelly.

2 Answers 2

5

Use the built in conversion function.

list_to_binary(X).

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks Dave! I had a quite a complex function concatinating variables and strings/integers/atoms etc. A college just went through it with me and it seems like Erlang deals with (what I was thinking of as Strings) as lists! Confusing but I understand it now, problem solved! Thanks!
Note that list_to_binary(List) assumes that all integers in List are in the range 0 to 255 (the Latin-1 range), and the resulting binary will have a 1-to-1 correspondence between bytes and list elements. To convert a list of arbitrary Unicode code points into a UTF-8 encoded binary (which can have multiple bytes per code point), use unicode:characters_to_binary(List) - read the unicode module documentation for details: erlang.org/doc/man/unicode.html
Or you can use << <<X/utf8>> || X <- L >>.
0

Thanks Dave! I had a quite a complex function concatinating variables and strings/integers/atoms etc.

In case you are interested:

convert(L) ->
    convert(L, <<>>).
convert([], Bin) ->
    Bin;
convert([H|T], Bin) ->
    convert(T, <<Bin/binary, H>>).

(what I was thinking of as Strings) as lists! Confusing

I think the reason that it's confusing is because sometimes the shell prints out a list as a string and sometimes it doesn't. In my opinion, things would be much clearer if the shell always output a list as a list unless you specifically requested a string.

4 Comments

Yes. The shell is helpful when you know more about the special things it sometimes does. True that. But sometimes it can be very confusing when learning Erlang. On the flip side, it is very good to the shell well because the shell is an excellent tool to look into a running production server (an Erlang Virtual Machine). So knowing the shell well will actually make you a better Erlang DevOp.
<< <<X>> || X <- L >> does just what your convert/1 does.
@Hynek-Pichi-Vychodil, Thanks. Why is it that you can write things like: [H|convert(Tail)] but not <<H, convert(Tail)>>? Does it have to do with the way binaries are optimized?
@7stud You can write <<H, (convert(Tail))/bytes>> but note that your version is far more efficient. Try it and check it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.