In Erlang how do I convert a String to a binary value?

倖福魔咒の 提交于 2019-12-05 08:47:55

问题


In Erlang how do I convert a string to a binary value?

String = "Hello"
%% should be
Binary = <<"Hello">>

回答1:


In Erlang strings are represented as a list of integers. You can therefore use the list_to_binary (built-in-function, aka BIF). Here is an example I ran in the Erlang console (started with erl):

1> list_to_binary("hello world").
<<"hello world">>



回答2:


the unicode (utf-8/16/32) character set needs more number of bits to express characters that are greater than 1-byte in length: this is why the above call failed for any byte value > 255 (the limit of information that a byte can hold, and which is sufficient for IS0-8859/ASCII/Latin1)

to correctly handle unicode characters you'd need to use

unicode:characters_to_binary() R1[(N>3)]

instead, which can handle both Latin1 AND unicode encoding.

HTH ...



来源:https://stackoverflow.com/questions/2268828/in-erlang-how-do-i-convert-a-string-to-a-binary-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!