erlang – How to extract a binary from a string?

Question:

I have the following list of decimals in Erlang:
"01000001" == [48, 49, 49, 49, 49, 49, 48]

I need to create a binary type from this list, then:
<<01000001>> == <<"A">>

I've tried converting with the list_to_binary/1 function, but it turns out:
<<"01000001">> == <<48, 49, 49, 49, 49, 49, 48>>

Is there any function that does this? Or what would be the best way to turn "01000001" into <<01000001>> ?

Answer:

If you need to "transform" "01000001" into <<"01000001">> , use the list_to_binary/1 function. See an example:

erl(0)> Binary = list_to_binary("01000001").
<<"01000001">>

erl(1)> binary_to_integer(Binary, 2).       
65

Remembering that <<"01000001">> is a syntactic sugar for <<48, 49, 48, 48, 48, 48, 48, 49>> , and that gets resolved at compile time. Such that if we try the following, we get an error:

erl(0)> Str = "01000001".
erl(1)> <<Str>>.         
** exception error: bad argument
     in function  eval_bits:eval_exp_field1/6 (eval_bits.erl, line 108)
     in call from eval_bits:eval_field/3 (eval_bits.erl, line 99)
     in call from eval_bits:expr_grp/4 (eval_bits.erl, line 68)
Scroll to Top