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条)

报告相同问题?

悬赏问题

  • ¥20 判断两个表是否完全相同
  • ¥20 工控机出现散热器转一下停一下这种情况,是什么原因造成的
  • ¥15 双显卡,启动docker容器报错。
  • ¥15 想编写一个期货跨期套利的程序
  • ¥15 一个线程在sleep的时候set一个信号会起作用吗
  • ¥100 需求高精度PT100设计电路和算法
  • ¥15 单片机配网,继电器开关,广播
  • ¥60 Qcustomplot绘制实时动态曲线
  • ¥20 运用matlab画x-y图
  • ¥15 用idea运行项目,运行tomcat报错:断言失败