Golang中二进制字节数组的终止指示符?
在Golang中,如果我有一个二进制数据的字节数组,如果它在一个较大的数组中,我如何确定实际数据的终止。例如,如果我执行以下操作,读取纯文本文件:Golang中二进制字节数组的终止指示符?,go,binary,bytearray,Go,Binary,Bytearray,在Golang中,如果我有一个二进制数据的字节数组,如果它在一个较大的数组中,我如何确定实际数据的终止。例如,如果我执行以下操作,读取纯文本文件: chunk := make([]byte, 1024) ..read some data into the chunk but only 10 bytes are filled from the file... 然后,我可以通过执行以下操作来确定数据的实际大小: n := bytes.IndexByte(chunk, 0) 当它是纯文本时
chunk := make([]byte, 1024)
..read some data into the chunk but only 10 bytes are filled from the file...
然后,我可以通过执行以下操作来确定数据的实际大小:
n := bytes.IndexByte(chunk, 0)
当它是纯文本时,n将给我实际数据的结尾-如果数据是二进制的,我怎么做 Read函数返回读取的字节数
然后可以创建该大小的子切片。
例如:
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
}
谢谢你,大卫!我注意到,在os.Open之后读取的文件中,我也得到了读取的字节数,而与字节数组的大小无关-这让我开始进一步研究这个问题,所以谢谢你。是的,大多数字节可读的东西都有相同的签名“func Read([]字节)(int,error)”。所以你用同样的代码来读取文件,套接字,嗯。。。其他给你字节的东西(画一个空白)。。。