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

报告相同问题?

悬赏问题

  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 MATLAB中streamslice问题
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 51单片机中C语言怎么做到下面类似的功能的函数(相关搜索:c语言)
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端