如何将二进制文件转换为 Elixir 中的结构列表?
How do I convert a binary into a list of structs in Elixir?
我有一个二进制文件如下:<<123, 249, 222, 67, 253, 128, 131, 231, 101>>
我想将其转换成这样的结构列表:
[%RGB{red: 123, green: 249, blue: 222}, %RGB{red: 67, green: 253, blue: 128}, %RGB{red: 131, green: 231, blue: 101}]
.
RGB
结构定义如下:
defmodule RGB do
defstruct red: 0, green: 0, blue: 0
end
我试过以下方法:
def to_rgb(data) when is_binary(data) do
stage = 0 # R:0, G:1, B:2, 3:Complete
rgb = %RGB{}
rgblist = []
for x <- :binary.bin_to_list(data) do
cond do
stage == 0 -> rgb = %{rgb | red: x}
stage == 1 -> rgb = %{rgb | blue: x}
stage == 2 -> rgb = %{rgb | green: x}
end
if stage == 3 do
rgblist = rgblist ++ [rgb]
stage = 0
end
end
rgblist
end
但它远非优雅且不起作用(return 值是一个空列表)。
您可以使用 bitstring generators 一次从二进制 3 中解析 r
、g
、b
值,并将它们放入结构中:
def to_rgb(data) when is_binary(data) and rem(byte_size(data), 3) == 0 do
for <<r, g, b <- data>> do
%RGB{red: r, green: g, blue: b}
end
end
输出:
[
%RGB{blue: 222, green: 249, red: 123},
%RGB{blue: 128, green: 253, red: 67},
%RGB{blue: 101, green: 231, red: 131}
]
我有一个二进制文件如下:<<123, 249, 222, 67, 253, 128, 131, 231, 101>>
我想将其转换成这样的结构列表:
[%RGB{red: 123, green: 249, blue: 222}, %RGB{red: 67, green: 253, blue: 128}, %RGB{red: 131, green: 231, blue: 101}]
.
RGB
结构定义如下:
defmodule RGB do
defstruct red: 0, green: 0, blue: 0
end
我试过以下方法:
def to_rgb(data) when is_binary(data) do
stage = 0 # R:0, G:1, B:2, 3:Complete
rgb = %RGB{}
rgblist = []
for x <- :binary.bin_to_list(data) do
cond do
stage == 0 -> rgb = %{rgb | red: x}
stage == 1 -> rgb = %{rgb | blue: x}
stage == 2 -> rgb = %{rgb | green: x}
end
if stage == 3 do
rgblist = rgblist ++ [rgb]
stage = 0
end
end
rgblist
end
但它远非优雅且不起作用(return 值是一个空列表)。
您可以使用 bitstring generators 一次从二进制 3 中解析 r
、g
、b
值,并将它们放入结构中:
def to_rgb(data) when is_binary(data) and rem(byte_size(data), 3) == 0 do
for <<r, g, b <- data>> do
%RGB{red: r, green: g, blue: b}
end
end
输出:
[
%RGB{blue: 222, green: 249, red: 123},
%RGB{blue: 128, green: 253, red: 67},
%RGB{blue: 101, green: 231, red: 131}
]