Timmmm
Timmmm

Reputation: 96625

Copy byte array to Go struct accounting for struct padding

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?

Upvotes: 1

Views: 201

Answers (1)

Timmmm
Timmmm

Reputation: 96625

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

Upvotes: 1

Related Questions