Converting several bytes in an array to another ty

2019-02-28 05:18发布

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条回答
劳资没心,怎么记你
2楼-- · 2019-02-28 05:40

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
}
查看更多
登录 后发表回答