使用位域比较 C 中的结构

标签 c memory struct bit-fields

所以我实在是无法理解这两个代码段的区别。我对位域的了解是我在内存中保留了多少位我将用于这个 int。但为什么负数出现在 2nd Struct 中?

#include<stdio.h>
#include<string.h>
typedef struct {
        unsigned int i:1;
        unsigned int k:31;
        int x;
}Struc1;
typedef struct{
        int i:1;
        int k:4;
        int x;
}Struc2;
int main()
{
        Struc1 s1={1,13,13};
        printf("%d %d %d\n",s1.i,s1.k,s1.x);
        Struc2 s2={1,13,13};
        printf("%d %d %d\n",s2.i,s2.k,s2.x);
        return 0;
}

输出:

1 13 13
-1 -3 13

最佳答案

这是 C 中 intsigned int 可能不同的地方。

使用位字段,没有signedunsignedint 可能被视为 signed intunsigned int。根据 OP 报告的输出,此实现定义的 int 行为类似于 signed int

typedef struct{
  int i:1;  // like signed int i:1; for OP
  int k:4;  // like signed int k:4; for OP
  int x;
}Struc2;

i 位域的范围可能是 [-1...0]k 的范围是 [-8 ...7]。通过 Struc2 s2={1,13,13}; 初始化一个有符号整数,其值超出其范围是实现定义的(详细信息:C11dr 6.3.1.3 3).

一个常见的实现定义行为是环绕。所以像 Struc2 s2 = {1-2, 13-16, 13};Struc2 s2 = {-1, -3, 13};


使用位域时,建议尽可能使用unsigned。如果需要 int 位域,请使用 signed int

关于使用位域比较 C 中的结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48306842/

相关文章:

c++ - 调试 lambda 内存损坏 ||自动监视 GDB 中的对象指针

C中链表的冗余计数

c - 将文件中的值放入结构中

c - 将自定义字符打印到 LCD

c - 如何在 C 中实现通用的、动态增长的数组?

c - 从 C 语言的输入文件中读取 CJK 字符

c - 当指针直接分配给字符串而不指向任何变量时,它是如何工作的?

ipad - 处理 iPad 设备上的低内存启动情况

c++ - 当我将 void 指针导入到具有指向共享对象中函数的指针的结构时,我没有收到警告

objective-c - 以编程方式 LZMA 解压缩静态 LZMA 压缩文件