尝试将整数插入字节数组中。

huangapple go评论72阅读模式
英文:

trying to insert integer into byte array

问题

我有一个字节数组:

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

我想知道如何用包含 300 的两个字节替换 app0[13:15]

请帮忙。我尝试了以下代码,但它甚至无法编译通过:

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

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)

答案1

得分: 1

我有点困惑,你到底想用这段代码做什么?

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

一个字节无法存储数值300,而且你有一个字节切片。我猜你想将数值300转换为两个字节:

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()
}

这里的技巧是你必须先获取一个字节数组,然后使用可变参数运算符(...)和append函数来替换数组的内部元素。

英文:

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.

答案2

得分: 1

例如,

package main

import "fmt"

func main() {
    app0 := []byte("\xff\xe0\x00\x10\x4a\x46\x49\x46\x00\x01\x01\x01\x00\x00\x00\x00\x00\x00")
    fmt.Println(app0)
    app0[13], app0[14] = 300>>8, 300&0xFF
    fmt.Println(app0)
}

输出:

[255 224 0 16 74 70 73 70 0 1 1 1 0 0 0 0 0 0]
[255 224 0 16 74 70 73 70 0 1 1 1 0 1 44 0 0 0]
英文:

For example,

package main

import "fmt"

func main() {
	app0 := []byte("\xff\xe0\x00\x10\x4a\x46\x49\x46\x00\x01\x01\x01\x00\x00\x00\x00\x00\x00")
	fmt.Println(app0)
	app0[13], app0[14] = 300>>8, 300&0xFF
	fmt.Println(app0)
}

Output:

[255 224 0 16 74 70 73 70 0 1 1 1 0 0 0 0 0 0]
[255 224 0 16 74 70 73 70 0 1 1 1 0 1 44 0 0 0]

huangapple
  • 本文由 发表于 2015年1月6日 08:39:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/27790333.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定