英文:
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
如何存储在内存中?
许多可能性:
- 大端序:无填充:0x12,0x34,0x56,0x78
- 大端序:填充为偶数:0x12,0x34,0x56,...,0x78,...
- 大端序:填充为四字节对齐:0x12,0x34,0x56,...,0x78,...,...,...
- 小端序:无填充:0x56,0x34,0x12,0x78
- 小端序:填充为偶数:0x56,0x34,0x12,...,0x78,...
- 小端序:填充为四字节对齐:0x56,0x34,0x12,...,0x78,...,...,...
- 其他字节序:
- 对于位域,仅类型
int
、unsigned
、bool
有明确定义,因此无效。 - 无:在示例中,经过优化的编译可以消除变量。
- ...
良好的代码不应关心它在内存中的存储方式。
如果代码确实需要特定的顺序,请使用 uint8_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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论