在 Go 中将数组中的多个字节转换为另一种类型

发布于 2024-10-05 19:48:46 字数 448 浏览 7 评论 0原文

我昨天才开始使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

蹲墙角沉默 2024-10-12 19:48:46

查看 encoding/binary 以及 bytes.Buffer

TL;DR 版本:

import (
    "encoding/binary"
    "bytes"
)

func main() {
    var s eightByteType
    binary.Read(bytes.NewBuffer(array[:]), binary.LittleEndian, &s)
}

这里需要注意一些事情:我们传递数组[:],或者您可以将数组声明为切片 ([]byte{1, 2, 3, 4, 5}) 并让编译器担心大小等,并且 eightByteType 不会按原样工作(IIRC),因为 binary.Read 不会触及私有字段。这会起作用:

type eightByteType struct {
    A, B uint32
}

Look at encoding/binary, as well as bytes.Buffer

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 ([]byte{1, 2, 3, 4, 5}) and let the compiler worry about sizes, etc, and eightByteType won't work as is (IIRC) because binary.Read won't touch private fields. This would work:

type eightByteType struct {
    A, B uint32
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文