douaoli5328 2016-08-03 11:48
浏览 57

将字节数组复制到Go结构中以进行结构填充

Suppose I have this C struct

struct Foo
{
    uint8_t a;
    // 3 bytes of padding
    uint32_t b;
}

And its equivalent in Go:

type Foo struct {
    a uint8
    b uint32
}

And I have a byte slice that contains the C struct:

data := []byte { 0x01, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04 }

What is the best way to get that data into the Go struct (and vice versa).

Note that I do want padding according to the normal C rules. The C struct is not packed.

For packed structs I could do something like this:

    data := []byte { 0x01, 0x01, 0x02, 0x03, 0x04 }
    f := Foo{}
    buf := bytes.NewBuffer(data)
    err := binary.Read(buf, binary.LittleEndian, &f)

What is the equivalent, taking padding into account?

  • 写回答

1条回答 默认 最新

  • duanbu1421 2016-08-03 12:39
    关注

    Ah I realised there is a relatively simple way to do it - just explicitly add dummy padding bytes into the Go struct:

    type Foo struct {
        a uint8
        _ [3]byte
        b uint32
    }
    

    Then you can use binary.Read()

    评论

报告相同问题?