C编译器如何处理位域?

维基百科

以下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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

C编译器如何处理枚举?

Scala编译器如何处理具体特征方法?

编译器如何处理枚举中的符号常量?

编译器如何处理数据类型?

编译器如何处理case语句?

编译器如何处理无符号整数的减法?

如何处理递归函数和迭代函数中的编译器错误 c2660?

C#编译器如何处理重载显式强制转换运算符?

一遍C编译器如何处理标签?

C 编译器如何处理使用未初始化的变量?

C ++ / g ++:在这种情况下,编译器如何处理内存分配?

C ++编译器(或链接器)如何知道如何处理cpp和标头类文件?

用编译语言编写的编译器如何处理错误?

C++编译器在多重继承的情况下如何处理成员变量内存偏移?

在C#编译器和虚拟机中如何处理lambda表达式?

C ++如何处理NAN?有没有一种标准的方法还是编译器相关的?

Scala编译器如何处理未使用的变量值?

访问者模式和编译器代码生成,如何处理分配?

python3 grpc编译器:如何处理.protos中的绝对和相对导入?

未使用的原语数组:javac和JIT编译器如何处理它?

编译器如何处理已部分应用的布尔参数?

Angular编译器如何处理具有相同名称的多个模板引用变量

Java编译器如何处理“公共接口A扩展B <A>”之类的代码

编译器如何处理超出范围的char值?

编译器如何处理始终为true或false的语句?

动态类型语言的编译器如何处理非局部变量的更改?

ARM编译器如何处理运行时错误?

Python编译器和虚拟机如何处理eval表达式?

“else if”是语言结构还是编译器如何处理 if/else 结构的结果?