英文:
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;
}
它在内存中的存储方式是怎样的?
英文:
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、...、...、...
- 其他字节序:
- 对于位域,只有
int
、unsigned
和bool
类型是明确定义的,因此无效。 - 优化的编译器可能会将变量消除,因此不会存储任何值。
- ...
良好的代码不应关心内存中的存储方式。
如果代码确实需要特定的顺序,请使用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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论