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

    评论

报告相同问题?

悬赏问题

  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染