为什么打印出来的结果是不一样的,unsigned field3给定不同的位字段打印出来的值不一样,而且既然声明为unsigned field3为什么按%d打出来还是-4?而sizeof(struct BitField)的值始终是8,我是在gcc下测试的.
#include <stdio.h>
struct BitField {
int field1 : 10;
signed field2 : 8;
unsigned field3 : 24;
};
struct Bit {
int field1 : 10;
signed field2 : 8;
unsigned field3 : 32;
};
int main(void)
{
struct BitField bitfiled;
struct Bit bit;
bitfiled.field1 = -5;
bitfiled.field2 = -3;
bitfiled.field3 = -4;
printf("bitfiled.field1 = %d, bitfiled.field2 = %d, bitfiled.field3 = %ul/n",
bitfiled.field1, bitfiled.field2, bitfiled.field3);
printf("sizeof(struct BitField) = %d/n", sizeof(struct BitField));
bit.field1 = -5;
bit.field2 = -3;
bit.field3 = -4;
printf("/nbit.field1 = %d, bit.field2 = %d, bit.field3 = %ul",
bit.field1, bit.field2, bit.field3);
printf("/nbit.field1 = %d, bit.field2 = %d, bit.field3 = %d/n",
bit.field1, bit.field2, bit.field3);
printf("sizeof(struct Bit) = %d/n", sizeof(struct Bit));
return 0;
}
=======================================================
执行结果:
bitfiled.field1 = -5, bitfiled.field2 = -3, bitfiled.field3 = 16777212l
sizeof(struct BitField) = 8
bit.field1 = -5, bit.field2 = -3, bit.field3 = 4294967292l
bit.field1 = -5, bit.field2 = -3, bit.field3 = -4
sizeof(struct Bit) = 8