Reputation: 728
This piece of code throws error:
iex(35)> a = <<18::size(7)>>
<<18::size(7)>>
iex(36)> b = <<100::size(7)>>
<<100::size(7)>>
iex(37)> <<a <> b>>
** (ArgumentError) argument error
Why this code fails?
How can I concatenate bitstrings using variables?
(I updated to example according to mudasobwa's remarks)
Upvotes: 3
Views: 3279
Reputation: 121020
How can I concatenate bitstrings using variables?
Kernel.<>/2
:iex|1 ▶ a = <<1, 2>>
#⇒ <<1, 2>>
iex|2 ▶ b = <<3, 4>>
#⇒ <<3, 4>>
iex|3 ▶ a <> b
#⇒ <<1, 2, 3, 4>>
It also works inside Kernel.SpecialForms.<<>>/1
:
iex|4 ▶ << a <> <<3, 4>> >>
#⇒ <<1, 2, 3, 4>>
Alternatively you might explicitly tell the compiler you use binary:
iex|5 ▶ << a :: binary, <<3, 4>> >>
#⇒ <<1, 2, 3, 4>>
iex|6 ▶ a = <<18::size(7)>>
iex|7 ▶ << a :: bitstring, <<100::size(7)>> >>
#⇒ <<37, 36::size(6)>>
Upvotes: 10
Reputation: 728
The correct answer is to use a bitstring
type hint:
iex(35)> a = <<18::size(7)>>
<<18::size(7)>>
iex(36)> b = <<100::size(7)>>
<<100::size(7)>>
iex(37)> <<a <> b>>
** (ArgumentError) argument error
iex(37)> <<a, b>>
** (ArgumentError) argument error
iex(37)> <<a::bitstring, b::bitstring>>
<<37, 36::size(6)>>
Upvotes: 3