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

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

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 (
    &quot;encoding/binary&quot;
    &quot;bytes&quot;
)

func main() {
    var s eightByteType
    binary.Read(bytes.NewBuffer(array[:]), binary.LittleEndian, &amp;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
}

huangapple
  • 本文由 发表于 2010年11月30日 05:42:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/4308385.html
匿名

发表评论

匿名网友

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

确定