duanqiao1949 2015-12-06 03:27
浏览 350
已采纳

Golang中二进制字节数组的终止指示符?

In Golang if I have a byte array of binary data how do I determine the termination of actual data if it is in a larger array. For example if I do the following, reading a file when it is plain text:

    chunk := make([]byte, 1024)
..read some data into the chunk but only 10 bytes are filled from the file...

I can then determine the actual size of the data by doing the following:

n := bytes.IndexByte(chunk, 0)

When it is plain text n will give me the end of the actual data - how do I do that if the data is binary?

  • 写回答

1条回答 默认 最新

  • duanqi5333 2015-12-06 04:00
    关注

    io.Reader's Read function returns the number of bytes read.

    You can then create a sub-slice of that size. For example:

    data := make([]byte,1024)
    n, err := reader.Read(arr)
    if err != nil {
        // do something with error
    } else {
        rightSized := data[:n] 
        // rightSized is []byte of N length now and shares the underlying 
        // backing array so it's both space and time efficient
        // this will contain whatever was read from the reader
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?