在Go中将数组中的几个字节转换为另一个类型 [英] Converting several bytes in an array to another type in Go

查看:462
本文介绍了在Go中将数组中的几个字节转换为另一个类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我昨天刚开始使用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
}

我可以轻松地取出数组的前8个字节,八字节类型?

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.

能够将一个字节块转换为任何东西都是我真正喜欢的东西之一。希望我仍然可以在Go中做。

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.

推荐答案

查看 encoding / binary ,以及 bytes.Buffer

TL; DR版本:

import (
    "encoding/binary"
    "bytes"
)

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

这里要注意几点:我们传递数组[:],或者你可以将数组声明为一个slice( [] byte {1 ,2,3,4,5} ),让编译器担心大小等,并且 eightByteType ),因为 binary.Read 不会接触私有字段。这将工作:

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
}

这篇关于在Go中将数组中的几个字节转换为另一个类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆