Skip to content

Instantly share code, notes, and snippets.

@jlouis
Created January 23, 2011 23:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jlouis/792594 to your computer and use it in GitHub Desktop.
Save jlouis/792594 to your computer and use it in GitHub Desktop.
binary_to_integer/1
-module(z).
-compile(export_all).
pow(0, 0) -> 0;
pow(0, _N) -> 1;
pow(K, N) -> N * pow(K-1, N).
binary_to_integer(B) when is_binary(B) ->
{_, N} = binary_to_integer1(B),
N.
binary_to_integer_naive(B) ->
list_to_integer(binary_to_list(B)).
binary_to_integer1(<<>>) -> {0, 0};
binary_to_integer1(<<D:1/binary, R/binary>>) ->
case D of
<<S>> when S == $- ->
{P, N} = binary_to_integer1(R),
{P, N * -1};
<<C>> when C >= $0 andalso C =< $9 ->
{P, N} = binary_to_integer1(R),
{P+1, N + (C - $0) * pow(P, 10)}
end.
test() ->
N = <<"1234567890">>,
M = z,
{X, _N} = timer:tc(M, binary_to_integer_naive, [N]),
{Y, _N} = timer:tc(M, binary_to_integer, [N]),
{X, Y}.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment