Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elixir: Convert list of bits to binary

Tags:

elixir

I have a list of integers representing bits; e.g. [1,0,0,1,1,0,0,1,0,0,0,1,1,1,0,0] and I would like to convert it into a binary i.e. <<153, 28>>, I know that the length of the list will always be a multiple of 8.

I have looked at the Elixir documentation, but I have not been able to find any help (I have looked for the exact function but also for a function for appending a bit to a binary).

I have written a function which solves the problem (below) but I hoped there was a better way as I think my function looks too complicated.

def list_to_binary(l) do 
  if length(l) >= 8 do
    << Enum.at(l, 0) :: size(1),
      Enum.at(l, 1) :: size(1),
      Enum.at(l, 2) :: size(1),
      Enum.at(l, 3) :: size(1),
      Enum.at(l, 4) :: size(1),
      Enum.at(l, 5) :: size(1),
      Enum.at(l, 6) :: size(1),
      Enum.at(l, 7) :: size(1)
    >> <> list_to_binary(Enum.drop l, 8)
  else
    if length(l) == 0 do
      <<>>
    else
      l = l ++ List.duplicate(0, 8 - length(l))
      list_to_binary(l)
    end
  end
end
like image 506
jakobht Avatar asked Oct 20 '25 12:10

jakobht


2 Answers

Use Kernel.SpecialForms.for/1 comprehension: it’s into keyword argument accepts anything implementing Collectable protocol and binary indeed does implement it.

for i <- [1,0,0,1,1,0,0,1,0,0,0,1,1,1,0,0], do: <<i::1>>, into: <<>>
#⇒ <<153, 28>>
like image 146
Aleksei Matiushkin Avatar answered Oct 23 '25 09:10

Aleksei Matiushkin


Similar to @mudasobwa's answer above, you can do

Enum.into([1,0,0,1,1,0,0,1,0,0,0,1,1,1,0,0], <<>>, fn bit -> <<bit :: 1>> end)

I think this is slightly cleaner as Enum.into can be placed into a pipeline easily.

like image 23
Michael Oliver Avatar answered Oct 23 '25 08:10

Michael Oliver



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!