Created
November 15, 2011 21:25
-
-
Save pfigue/1368405 to your computer and use it in GitHub Desktop.
From binary to decimal, in erlang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
can you explain the code?