title: Elixir parse binary data?
body: <p>​for example:</p>
  
  <p>I have a binary look like this: </p>
  
  <pre><code> bin1 = "2\nok\n3\nbcd\n\n"​
  </code></pre>
  
  <p>or </p>
  
  <pre><code> bin2 = "2\nok\n3\nbcd\n1\na\n\n"​
  </code></pre>
  
  <p>and so on...</p>
  
  <p>The format is </p>
  
  <pre><code> byte_size  \n  bytes \n byte_size  \n  bytes \n  \n 
  </code></pre>
  
  <p>I want parse binary get</p>
  
  <pre><code>  ["ok", "bcd"]
  </code></pre>
  
  <p>how to implement in  Elixir or Erlang ?</p>
  
  <h3>Go version</h3>
  
  <p>a Go version parse this</p>
  
  <pre><code>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("&gt; [%s]\n", p);
          if len(p) == 0 || (len(p) == 1 &amp;&amp; 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 &lt; 0 {
              return nil
          }
          if offset+size &gt;= c.recv_buf.Len() {
              break
          }
  
          v := buf[offset : offset+size]
          resp = append(resp, string(v))
          offset += size + 1
      }
  
      return []string{}
  }
  </code></pre>
  
  <p>Thanks </p>