英文:
Converting several bytes in an array to another type in Go
问题
我昨天刚开始学Go,所以对于这个愚蠢的问题提前道歉。
假设我有一个字节数组,如下所示:
func main(){
arrayOfBytes := [10]byte{1,2,3,4,5,6,7,8,9,10}
}
现在,如果我想要取该数组的前四个字节,并将其作为一个整数使用,该怎么办?或者,我有一个如下所示的结构体:
type eightByteType struct {
a uint32
b uint32
}
我能否轻松地取出数组的前8个字节,并将其转换为eightByteType类型的对象?
我意识到这是两个不同的问题,但我认为它们可能有相似的答案。我已经查阅了文档,但没有找到一个很好的示例来实现这个。
能够将一块字节转换为任何类型是我在C中非常喜欢的一件事情。希望我在Go中仍然可以做到。
英文:
I just started yesterday with Go so I apologise in advance for the silly question.
Imagine that I have a byte array such as:
func main(){
arrayOfBytes := [10]byte{1,2,3,4,5,6,7,8,9,10}
}
Now what if I felt like taking the first four bytes of that array and using it as an integer? Or perhaps I have a struct that looks like this:
type eightByteType struct {
a uint32
b uint32
}
Can I easily take the first 8 bytes of my array and turn it into an object of type eightByteType?
I realise these are two different questions but I think they may have similar answers. I've looked through the documentation and haven't seen a good example to achieve this.
Being able to cast a block of bytes to anything is one of the things I really like about C. Hopefully I can still do it in Go.
答案1
得分: 3
看一下encoding/binary
,以及bytes.Buffer
TL;DR版本:
import (
"encoding/binary"
"bytes"
)
func main() {
var s eightByteType
binary.Read(bytes.NewBuffer(array[:]), binary.LittleEndian, &s)
}
这里需要注意几点:我们传递了array[:],或者你可以将数组声明为切片([]byte{1, 2, 3, 4, 5}
),让编译器自动处理大小等问题,而且eightByteType不能直接使用(如果我没记错的话),因为binary.Read
不会操作私有字段。这样会起作用:
type eightByteType struct {
A, B uint32
}
英文:
Look at <code>encoding/binary</code>, as well as <code>bytes.Buffer</code>
TL;DR version:
import (
"encoding/binary"
"bytes"
)
func main() {
var s eightByteType
binary.Read(bytes.NewBuffer(array[:]), binary.LittleEndian, &s)
}
A few things to note here: we pass array[:], alternatively you could declare your array as a slice instead (<code>[]byte{1, 2, 3, 4, 5}</code>) and let the compiler worry about sizes, etc, and <code>eightByteType</code> won't work as is (IIRC) because <code>binary.Read</code> won't touch private fields. This would work:
type eightByteType struct {
A, B uint32
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论