C语言结构体和共用体相关问题
#include<stdio.h>#if(1)
typedef union
{
unsigned int Val; //b15...b0
struct
{ //显示数据类型声明
char b8:2;
char b9:1;
char b10 :1;
char b11 :1;
char b12 :1;
char b13 :1;
char b14 :1;
char b15 :1;
char b0:1;
char b1:1;
char b2:1;
char b3:1;
char b4:1;
char b5:1;
char b6:1;
char b7:1;
}OneBit;
}StructWordData;
StructWordData ReadKeyVal;
int main( void )
{
int a,b;
ReadKeyVal.OneBit.b8 = 3;
a = ReadKeyVal.Val;
printf("a=%d\n",a);
b = ReadKeyVal.OneBit.b8;
printf("b=%d\n",b);
}
#endif
为什么这段代码运行结果b的值是-1 本帖最后由 jhq999 于 2021-9-6 16:28 编辑
看到负数第一步就应该想到符号问题
unsignedchar
typedef union
{
unsigned int Val; //b15...b0
struct
{ //显示数据类型声明
unsigned char b8:2;
unsigned char b9:1;
unsigned char b10 :1;
unsigned char b11 :1;
unsigned char b12 :1;
unsigned char b13 :1;
unsigned char b14 :1;
unsigned char b15 :1;
unsigned char b0:1;
unsigned char b1:1;
unsigned char b2:1;
unsigned char b3:1;
unsigned char b4:1;
unsigned char b5:1;
unsigned char b6:1;
unsigned char b7:1;
}OneBit;
}StructWordData; jhq999 发表于 2021-9-6 16:25
看到负数第一步就应该想到符号问题
unsignedchar
明白了,非常感谢
页:
[1]