Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

erlang

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

String = "Hello" %% should be Binary = <<"Hello">> 
like image 573
yazz.com Avatar asked Feb 15 '10 20:02

yazz.com


People also ask

How do you convert a string to a binary number?

To convert a string to binary, we first append the string's individual ASCII values to a list ( l ) using the ord(_string) function. This function gives the ASCII value of the string (i.e., ord(H) = 72 , ord(e) = 101). Then, from the list of ASCII values we can convert them to binary using bin(_integer) .

Is binary in Erlang?

Use a data structure called a binary to store large quantities of raw data. Binaries store data in a much more space efficient manner than in lists or tuples, and the runtime system is optimized for the efficient input and output of binaries.

Is string an Erlang?

Strings are lists in erlang (most of the time). The most common reason you would need to do this is a nested lists in a tree where some of the sub-lists are strings which need to be treated as a list entry not a subtree. Without tagging the list operations like flatten and tree traversal become much more difficult.


2 Answers

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">> 
like image 108
tux21b Avatar answered Sep 16 '22 16:09

tux21b


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 ...

like image 24
ombud Avatar answered Sep 17 '22 16:09

ombud