Skip to content

Instantly share code, notes, and snippets.

@pfigue
Created November 15, 2011 21:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pfigue/1368405 to your computer and use it in GitHub Desktop.
Save pfigue/1368405 to your computer and use it in GitHub Desktop.
From binary to decimal, in erlang
-module(bin2dec).
-export([bin2dec/1, bin2dec_/2]).
bin2dec("") ->
0;
bin2dec(List) -> bin2dec_(List, 0).
bin2dec_([], Sum) ->
Sum;
bin2dec_([48 | Tail], Sum) -> %48 is ascii code for 0
bin2dec_(Tail, Sum * 2);
bin2dec_([49 | Tail], Sum) -> %49 is ascii code for 1
bin2dec_(Tail, Sum * 2 + 1).
%% Example:
%% $ erl
%% [...]
%% 55> c(bin2dec).
%% {ok,bin2dec}
%% 57> bin2dec:bin2dec("110").
%% 6
%% 58> bin2dec:bin2dec("100").
%% 4
@tejaskane
Copy link

can you explain the code?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment