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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作