dongyoufo5672 2015-01-06 00:39
浏览 9
已采纳

试图将整数插入字节数组

I have an array of bytes

app0 := []byte("\xff\xe0\x00\x10\x4a\x46\x49\x46\x00\x01\x01\x01\x00\x00\x00\x00\x00\x00")

I am trying to figure out how to replace app0[13:15] with two bytes containing 300.

Please help. I tried the following but it won't even compile:

app0[13:15] = []byte(300)
  • 写回答

2条回答 默认 最新

  • duanchuang6978 2015-01-06 01:01
    关注

    I'm a little confused what you are even trying to do with

    app0[13:15] = []byte(300)
    

    A single byte can't hold the value 300, and you have a slice of bytes. I'll assume you want the value 300 converted into two bytes:

    import (
        "fmt"
        "bytes"
        "encoding/binary"
    )
    
    func main() {
        app0 := []byte("\xff\xe0\x00\x10\x4a\x46\x49\x46\x00\x01\x01\x01\x00\x00\x00\x00\x00\x00")
        app0 =  append(app0[:13], append(intToBytes(uint16(300)), app0[15:]...)...)
        fmt.Println(app0)
    }
    
    func intToBytes(i uint16) []byte {
        buf := new(bytes.Buffer)
        _ = binary.Write(buf, binary.LittleEndian, i)
        return buf.Bytes()
    }
    

    https://play.golang.org/p/qADHwCCFQG

    The trick here is you have to actually get an array of bytes, and then you can use the variadic operator (...) and then append function to replace the inner elements of the array.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 Matlab打开默认名称带有/的光谱数据
  • ¥50 easyExcel模板 动态单元格合并列
  • ¥15 res.rows如何取值使用
  • ¥15 在odoo17开发环境中,怎么实现库存管理系统,或独立模块设计与AGV小车对接?开发方面应如何设计和开发?请详细解释MES或WMS在与AGV小车对接时需完成的设计和开发
  • ¥15 CSP算法实现EEG特征提取,哪一步错了?
  • ¥15 游戏盾如何溯源服务器真实ip?需要30个字。后面的字是凑数的
  • ¥15 vue3前端取消收藏的不会引用collectId
  • ¥15 delphi7 HMAC_SHA256方式加密
  • ¥15 关于#qt#的问题:我想实现qcustomplot完成坐标轴
  • ¥15 下列c语言代码为何输出了多余的空格