【发布时间】:2015-02-14 06:40:36
【问题描述】:
我这样做:
<<a :: big-size(16), b :: big-size(16), c :: big-size(16)>> = <<0, 1, 0, 2, 0, 3>>
然后结果将是:
a = 1
b = 2
c = 3
但我真正需要的是:
a = [1, 2, 3]
有什么方法可以实现吗?
【问题讨论】:
标签: elixir
我这样做:
<<a :: big-size(16), b :: big-size(16), c :: big-size(16)>> = <<0, 1, 0, 2, 0, 3>>
然后结果将是:
a = 1
b = 2
c = 3
但我真正需要的是:
a = [1, 2, 3]
有什么方法可以实现吗?
【问题讨论】:
标签: elixir
如果我正确地阅读了您在 greggreg 的回答中的评论,这是一种方法:
<< size::8, rest::binary>> = <<3,0,25,1,1,2,1,6,4,3>>
<< data::size(size)-unit(16)-binary, rest::binary>> = rest
elements = for << <<element::16>> <- data>>, do: element
# At this point, elements is the list of n 16 bit integers
# (n being the first byte), and rest is the rest of the binary
【讨论】:
不直接与模式匹配。您只能匹配整个结构或子结构。您不能将一种结构强制转换为另一种结构。
不过,再多一行代码即可:
<<a :: 16, b :: 16, c :: 16>> = <<0, 1, 0, 2, 0, 3>>
a = [a, b, c] # a equals [1, 2, 3]
或者你可以写一个理解来做到这一点:
a = for <<b :: 16 <- <<0, 1, 0, 2, 0, 3>> >>, do: b
【讨论】:
size(size)-unit(16)-binary 表单的存在并学到了一些东西!