我做了一个字段大小为1位的字段,而int不是使用unsigned.后来,当我试图检查字段的值时,我发现值为-1.我使用此代码检查二进制represantation和我的位字段的值:
#include <stdio.h>
#include <stdlib.h>
union {
struct {
int bit:1;
} field;
int rep;
} n;
int main() {
int c, k;
n.field.bit=1;
for (c = 31; c >= 0; c--)
{
k = n.rep >> c;
if (k & 1)
printf("1");
else
printf("0");
}
printf("\n %d \n", n.field.bit);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出为:00000000000000000000000000000001
-1
在那种情况下,为什么我的位字段的值是-1,当我使用signed int而不是unsigned时,它总是一个负数?