Elixir: Convert list of bits to binary

社会主义新天地 提交于 2020-03-03 12:15:42

问题


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

回答1:


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>>



回答2:


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.



来源:https://stackoverflow.com/questions/50365157/elixir-convert-list-of-bits-to-binary

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!