In Erlang how do I convert a string
to a binary
value?
String = "Hello" %% should be Binary = <<"Hello">>
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) .
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.
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.
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">>
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 ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With