所以我实在是无法理解这两个代码段的区别。我对位域的了解是我在内存中保留了多少位我将用于这个 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 中 int
、signed int
可能不同的地方。
使用位字段,没有signed
或unsigned
的int
可能被视为 signed int
或 unsigned 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/