Byte order in C bit field?

huangapple go评论79阅读模式
英文:

Byte order in C bit field?

问题

考虑 uint32_t n = 0x12345678;它在大端序(BE)或小端序(LE)机器上存储,就像图片所示;现在我有一个定义如下的结构体:

struct DATA {
    uint32_t a : 24;
    uint32_t b : 8;
};

int main() {
    struct DATA data;
    data.a = 0x123456;
    data.b = 0x78;
    return 0;
}

它在内存中的存储方式是怎样的?

英文:

Byte order in C bit field?

Consider uint32_t n = 0x12345678; it stores in BE machine or LE machine, like the picture shows; now I have a structure defined like this

struct DATA {
    uint32_t a : 24;
    uint32_t b : 8;
};

int main() {
    struct DATA data;
    data.a = 0x123456;
    data.b = 0x78;
    return 0;
}

How does it store in memory?

答案1

得分: 1

如何在内存中存储取决于多种可能性:

  • 大端序(BE):无填充:0x12、0x34、0x56、0x78
  • 大端序(BE):填充为偶数:0x12、0x34、0x56、...、0x78、...
  • 大端序(BE):填充为四字节对齐:0x12、0x34、0x56、...、0x78、...、...、...
  • 小端序(LE):无填充:0x56、0x34、0x12、0x78
  • 小端序(LE):填充为偶数:0x56、0x34、0x12、...、0x78、...
  • 小端序(LE):填充为四字节对齐:0x56、0x34、0x12、...、0x78、...、...、...
  • 其他字节序:
  • 对于位域,只有intunsignedbool类型是明确定义的,因此无效。
  • 优化的编译器可能会将变量消除,因此不会存储任何值。
  • ...

良好的代码不应关心内存中的存储方式。
如果代码确实需要特定的顺序,请使用uint8_t数组而不是位域。


注意:许多编译器不会像示例中那样将uint32_t存储在奇数边界上。

英文:

> How does it store in memory?

Many possibilities:

  • BE: no padding: 0x12, 0x34, 0x56, 0x78
  • BE: padding to even: 0x12, 0x34, 0x56, ..., 0x78, ...
  • BE: padding to quad: 0x12, 0x34, 0x56, ..., 0x78, ..., ..., ...
  • LE: no padding: 0x56, 0x34, 0x12, 0x78
  • LE: padding to even: 0x56, 0x34, 0x12, ..., 0x78, ...
  • LE: padding to quad: 0x56, 0x34, 0x12, ..., 0x78, ..., ..., ...
  • Other Endians:
  • Invalid as only types int, unsigned, bool well defined for bit-fields.
  • None: as an optimized compile can eliminate the variable as used in the example.
  • ...

Good code should not care how it is stored in memory.
If code really needs a certain order, use an array of uint8_t instead of a bit-field.


Note: many compilers will not store a uint32_t on an odd boundary as in the example.

huangapple
  • 本文由 发表于 2023年8月9日 10:51:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/76864272.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定