以下bit field
示例代码来自此处。它声称具有更好的存储效率。但是我想知道编译器如何处理位字段?
我猜的C编译器必须生成逐位操作额外的指令。因此,尽管减小了数据大小,但增加了代码大小。
任何熟悉C编译器的人都可以了解一下吗?
#include <stdio.h>
// A space optimized representation of date
struct date
{
// d has value between 1 and 31, so 5 bits
// are sufficient
unsigned int d: 5;
// m has value between 1 and 12, so 4 bits
// are sufficient
unsigned int m: 4;
unsigned int y;
};
int main()
{
printf("Size of date is %d bytes\n", sizeof(struct date));
struct date dt = {31, 12, 2014};
printf("Date is %d/%d/%d", dt.d, dt.m, dt.y);
return 0;
}
因此,尽管减小了数据大小,但增加了代码大小。
通常,这是正确的:这是在更紧凑的存储与更快的访问之间的权衡。
例如,这是我的编译器为printf
您的位域示例中的语句生成的结果:
movq _dt@GOTPCREL(%rip), %rax
movzwl (%rax), %edx
movl %edx, %esi
andl $31, %esi ; -- extract the 5 bits representing day
shrl $5, %edx ; -+ extract the four bits for the month
andl $15, %edx ; /
movl 4(%rax), %ecx ; -- year doesn't require any bit manipulation
leaq L_.str.1(%rip), %rdi
xorl %eax, %eax
callq _printf
为了进行比较,相同的代码whendate
很简单struct
:
movq _dt@GOTPCREL(%rip), %rax
movl (%rax), %esi ; -- day
movl 4(%rax), %edx ; -- month
movl 8(%rax), %ecx ; -- year
leaq L_.str.1(%rip), %rdi
xorl %eax, %eax
callq _printf
当然,所有这些都是特定于编译器和平台的。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句