Converting several bytes in an array to another type in Go

前端 未结 1 347
没有蜡笔的小新
没有蜡笔的小新 2021-01-21 06:17

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(){
    arrayOfByt         


        
相关标签:
1条回答
  • 2021-01-21 06:48

    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
    }
    
    0 讨论(0)
提交回复
热议问题