Elixir:将位列表转换为二进制 [英] Elixir: Convert list of bits to binary
问题描述
我有一个代表位的整数列表;例如 [1,0,0,1,1,0,0,1,0,0,0,1,1,1,0,0]
,我想要将其转换为二进制文件,即< 153,28>
,我知道列表的长度将始终是8的倍数。
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.
我查看了Elixir文档,但未能找到任何帮助(我查找了确切的函数,但也查找了向二进制文件追加一点的函数)。
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
推荐答案
使用 Kernel.SpecialForms.for / 1
理解:它是 into
关键字参数接受实现 可收集
协议的任何内容和 binary
确实实现了它。
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>>
这篇关于Elixir:将位列表转换为二进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!