C++ struct alignment question

后端 未结 6 829
清歌不尽
清歌不尽 2020-12-05 09:12

I have a predefined struct (actually several) where variables span across 32-bit word boundary. In Linux (and Windows using GCC) I am able to get my structs to pack to the

6条回答
  •  南笙
    南笙 (楼主)
    2020-12-05 09:43

    Shorter example with only conforming code


    struct unpacked {  // apparently my other example was too long and confusing
        uint32_t a;    // ...here is a much shorter example with only the conforming
        uint32_t b;    // ...code. (The other program had the gcc-specific declaration,
        uint32_t c;    // but only for test code. Still, it was a bit long.)
        uint32_t troubleMaker;
    };
    
    struct unpacked su;
    char *bits = "Lorem ipsum dolor";
    
    void f(void) {
      uint32_t x;
    
      memcpy(&x, bits, 4);
      su.a = x & 7;
      su.b = x >> 3 & 1;
      su.c = x >> 4 & 0x7fff;
      memcpy(&x, bits + 2, 4);
      su.troubleMaker = x >> 3 & 0xffff;
      return 0;
    }
    

提交回复
热议问题