Binary integer & # 8594; Erlang

I have a binary M such that 34 = will always be present, and the rest can vary between any number of digits, but will always be an integer.

M = [<<"34=21">>] 

When I run this command, I get a response like

 hd([X || <<"34=", X/binary >> <- M]) Answer -> <<"21">> 

How can I get this integer with the utmost care to make it as efficient as possible?

+6
integer binary erlang
source share
3 answers
 [<<"34=",X/binary>>] = M, list_to_integer(binary_to_list(X)). 

It gives an integer 21

+20
source share

With R16B, you can use BIF binary_to_integer/1 :

OTP-10300

Four new erlang:binary_to_integer/1,2 , erlang:binary_to_integer/1,2 , erlang:integer_to_binary/1 , erlang:binary_to_float/1 and erlang:float_to_binary/1,2 . These beefs work in the same way as their peers from the list work, except that they operate binary files. In most cases, converting from binary to is faster than converting from lists to lists.

These beefs are automatically imported into the erlang source files and can therefore be used without the erlang prefix.

So it will look like this:

 [<<"34=",X/binary>>] = M, binary_to_integer(X). 
+17
source share

The string representation of a number can be converted to N-48. For multi-digit numbers, you can add in binary, multiplying by the strength of the position of the digit:

 -spec to_int(binary()) -> integer(). to_int(Bin) when is_binary(Bin) -> to_int(Bin, {size(Bin), 0}). to_int(_, {0, Acc}) -> erlang:trunc(Acc); to_int(<<N/integer, Tail/binary>>, {Pos, Acc}) when N >= 48, N =< 57 -> to_int(Tail, {Pos-1, Acc + ((N-48) * math:pow(10, Pos-1))}). 

Performance in this case is about 100 times slower than when using the list_to_integer(binary_to_list(X)) parameter.

+1
source share

All Articles