dqy0707 2014-05-05 21:27
浏览 127
已采纳

如何在Golang中将16位整数写入多个字节?

Let's say I have the 16 bit integer 259 (0000000100000011 in binary) and I want to write it to a byte stream in Go. A byte is only 8 bits, so how can I split the integer across multiple bytes?

  • 写回答

1条回答 默认 最新

  • douzhajie7168 2014-05-05 21:27
    关注

    Use the binary.Write method of the encoding/binary package.

    buf := new(bytes.Buffer)
    err := binary.Write(buf, binary.BigEndian, uint16(259))
    if err != nil {
        fmt.Println("binary.Write failed:", err)
    }
    
    // This should be two bytes with your encoded integer.
    fmt.Println(buf.Bytes())
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部