Elixir解析二进制数据?

时间:2014-06-26 15:58:27

标签: erlang elixir

例如:

我的二进制看起来像这样:

 bin1 = "2\nok\n3\nbcd\n\n"​

 bin2 = "2\nok\n3\nbcd\n1\na\n\n"​

依旧......

格式为

 byte_size  \n  bytes \n byte_size  \n  bytes \n  \n 

我想要解析二进制获取

  ["ok", "bcd"]

如何在Elixir或Erlang中实现?

转到版本

Go版本解析此

func (c *Client) parse() []string {
    resp := []string{}
    buf := c.recv_buf.Bytes()
    var idx, offset int
    idx = 0
    offset = 0

    for {
        idx = bytes.IndexByte(buf[offset:], '\n')
        if idx == -1 {
            break
        }
        p := buf[offset : offset+idx]
        offset += idx + 1
        //fmt.Printf("> [%s]\n", p);
        if len(p) == 0 || (len(p) == 1 && p[0] == '\r') {
            if len(resp) == 0 {
                continue
            } else {
                c.recv_buf.Next(offset)
                return resp
            }
        }

        size, err := strconv.Atoi(string(p))
        if err != nil || size < 0 {
            return nil
        }
        if offset+size >= c.recv_buf.Len() {
            break
        }

        v := buf[offset : offset+size]
        resp = append(resp, string(v))
        offset += size + 1
    }

    return []string{}
}

谢谢

2 个答案:

答案 0 :(得分:8)

更灵活的解决方案:

result = bin 
|> String.split("\n") 
|> Stream.chunk(2)
|> Stream.map(&parse_bytes/1)
|> Enum.filter(fn s -> s != "" end)

def parse_bytes(["", ""]), do: ""
def parse_bytes([byte_size, bytes]) do
  byte_size_int = byte_size |> String.to_integer
  <<parsed :: binary-size(byte_size_int)>> = bytes
  parsed
end

答案 1 :(得分:4)

我写了一个解决方案:

  defp parse("\n") do
    []
  end

  defp parse(data) do
    {offset, _} = :binary.match(data, "\n")
    size = String.to_integer(binary_part(data, 0, offset))
    value = binary_part(data, offset + 1, size)

    len = offset + 1 + size + 1
    [value] ++ parse(binary_part(data, len, byte_size(data) - len))
  end

Elixir邮件列表提供了另一个邮件列表:

  defp parse_binary("\n"), do: []

  defp parse_binary(binary) do
    {size, "\n" <> rest} = Integer.parse(binary)
    <<chunk :: [binary, size(size)], "\n", rest :: binary>> = rest
    [chunk|parse_binary(rest)]
  end