Skip to content

Instantly share code, notes, and snippets.

@leikind
Created October 31, 2014 09:24
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 leikind/03d2a73effffcca9acb4 to your computer and use it in GitHub Desktop.
Save leikind/03d2a73effffcca9acb4 to your computer and use it in GitHub Desktop.
Binary to decimal
defmodule Bin2Dec do
import List, only: [duplicate: 2]
import Enum
def bin2dec(bin) when is_binary(bin) do
bin
|> String.codepoints
|> reverse
|> map( &(String.to_integer/1))
|> with_index
|> map(fn({d, idx}) -> duplicate(2, idx) |> reduce(d, &(*/2) ) end)
|> sum
end
end
IO.inspect Bin2Dec.bin2dec("11")
IO.inspect Bin2Dec.bin2dec("111")
IO.inspect Bin2Dec.bin2dec("101")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment