在 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 个字节并将其转换为八字节类型的对象吗?
我意识到这是两个不同的问题,但我认为他们可能有相似的答案。我浏览了文档,但没有看到实现此目的的好示例。
能够将字节块转换为任何内容是我真正喜欢 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
查看
encoding/binary
以及bytes.Buffer
TL;DR 版本:
这里需要注意一些事情:我们传递数组[:],或者您可以将数组声明为切片 (
[]byte{1, 2, 3, 4, 5}
) 并让编译器担心大小等,并且eightByteType
不会按原样工作(IIRC),因为binary.Read
不会触及私有字段。这会起作用:Look at
encoding/binary
, as well asbytes.Buffer
TL;DR version:
A few things to note here: we pass array[:], alternatively you could declare your array as a slice instead (
[]byte{1, 2, 3, 4, 5}
) and let the compiler worry about sizes, etc, andeightByteType
won't work as is (IIRC) becausebinary.Read
won't touch private fields. This would work: