[erlang-questions] String versus variable in binary literal

Fred Hebert <>
Wed May 16 13:46:26 CEST 2012


When dealing with strings of text, please do not use list_to_binary or 
binary_to_list, as they only handle lists of bytes (0..255).

What you might want instead is unicode:characters_to_binary(Chars, 
InEncoding, OutEncoding), where Chars can be either:

  * an iolist (list + binaries of bytes)
  * a list of codepoints as integers (for Unicode)
  * a list encoded as latin-1
  * binaries encoded as latin-1, utf-8, utf-16 or utf-32

And InEncoding and OutEncoding can be any of: utf8 (also aliased as 
unicode), utf16, utf32, and latin1.

It will generally be safer (especially if you want to deal with Unicode) 
to use this function instead of list_to_binary, as it should crash 
whenever a given character is > 255, which might happen quite a lot 
outside of ASCII.

On 12-05-16 5:00 AM, Ivan Uemlianin wrote:

> On 16/05/2012 09:49, Michel Rijnders wrote:
>> Hi,
>>
>> Confused newbie here. Can someone please explain the following:
>>
>> 1> <<"foo">>.
>> <<"foo">>
>> 2>  Foo = "foo".
>> "foo"
>> 3> <<Foo>>.
>> ** exception error: bad argument
>>
>> What's the error in the last case?
>>
>> Best,
>> Michel
>
> You can use list_to_binary/1 for the same effect:
>
> 1> <<"foo">>.
> <<"foo">>
> 2> Foo = "foo".
> "foo"
> 3> list_to_binary(Foo).
> <<"foo">>
>
> Ivan
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20120516/55930a7f/attachment.html>


More information about the erlang-questions mailing list