2
votes

I do this:

<<a :: big-size(16), b :: big-size(16), c :: big-size(16)>> = <<0, 1, 0, 2, 0, 3>>

And then result will be:

a = 1
b = 2
c = 3

But what I actually need is:

a = [1, 2, 3]

Is there any way to achieve that?

2

2 Answers

5
votes

If I read your comment in answer by greggreg correctly, this is one way of doing it:

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

Not with pattern matching directly. You can only match on the whole structure or a sub structure. You can't coerce one structure into another.

One more line of code gets you there though:

<<a :: 16, b :: 16, c :: 16>> = <<0, 1, 0, 2, 0, 3>>
a = [a, b, c] # a equals [1, 2, 3]

Or you could write a comprehension to do it:

a = for <<b :: 16 <-  <<0, 1, 0, 2, 0, 3>> >>, do: b