Skip to content

Instantly share code, notes, and snippets.

@CMCDragonkai
Created October 27, 2014 09:21
Show Gist options
  • Save CMCDragonkai/d8cb594540efd28f0fcf to your computer and use it in GitHub Desktop.
Save CMCDragonkai/d8cb594540efd28f0fcf to your computer and use it in GitHub Desktop.
Elixir: Converting a bitstring to integer. Basically converting base 1 to base 2.
# Note that you can also do things like for << b::2 <- <<1::1, 1::1, 1::1, 0::1>> >>, do: b
# It's pretty cool, it makes sure the b variable is composed of 2 bits. So it will segment the bitstring to represent and have create a b for every 2 bits.
# Binary Comprehension over a bitstring of size 1 bits
list = for << b::1 <- <<1::1, 1::1, 1::1, 0::1>> >>, do: b
# The Goal is the turn <<1::1, 1::1, 1::1, 0::1>> into a base 2 integer, which would be 14
# POWER is like 2^2 which means 2*2. So if x^y. Then there y recursions of x * x.
defmodule Math do
def pow(num, power) do
do_pow num, power, 1
end
defp do_pow(_num, 0, acc) do
acc
end
defp do_pow(num, power, acc) when power > 0 do
do_pow(num, power - 1, acc * num)
end
end
# Reverse the bitstring (binary 1s and 0s). And use this algorithm: http://www.wikihow.com/Convert-from-Binary-to-Decimal
# It's all about converting to base 2.
defmodule Convert do
def binary_list_to_integer (list) do
do_binary_list_to_integer Enum.reverse(list), 0, 0
end
defp do_binary_list_to_integer([], _power, acc) do
acc
end
defp do_binary_list_to_integer([head | tail], power, acc) do
do_binary_list_to_integer tail, (power+1), (acc + (head*Math.pow(2, power)))
end
end
x = Convert.binary_list_to_integer (list)
IO.puts x
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment