douna1895 2019-06-18 22:18
浏览 514

从[] byte读取uint8而不创建byte.Buffer

How to read a unit8 from []byte without creating a bytes.Buffer. The value has been written to the buffer like this,

buf := new(bytes.Buffer)
binary.Write(buf, binary.BigEndian, uint32(1))
binary.Write(buf, binary.BigEndian, uint8(1))
b := buf.Bytes()

While decoding, it can easily be done for uint32, like the following...

len := binary.BigEndian.Uint32(b[:4])

But for the uint8, the only way to retrieve the value that I could come up with, is to create a buffer and then read the first byte,

buf := new(bytes.Buffer)
_, err := buf.Write(b[4:5])
// error handling ...
id = buf.ReadByte()

It seems like there's no method in the encoding/binary pkg for uint8 value retrieval. And I guess there's probably some good reason behind it.

Question: Is there any other way to read uint8 from that []byte without creating a Buffer??

  • 写回答

2条回答 默认 最新

  • douman9420 2019-06-18 22:28
    关注

    Us an index expression to get an single uint8 from a slice.

    len := binary.BigEndian.Uint32(b[:4])
    id := b[4]  // <-- index expression
    

    Note that byte is an alias for uint8.

    评论

报告相同问题?

悬赏问题

  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP