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

报告相同问题?