用联合体实现一个int型和四个char型 无符号和有符号整型

//用联合体实现一个int型和四个char型
union MyUnion
{//该联合体中,n与c共用一块内存空间,一个n等价与四个c,只不过表现形式不一样
	int n;
	char c[4];
};
//测试函数
void Test(char *buff,int number)
{
	 MyUnion uObject;
	 uObject.n = number;
	*(buff + 0)=uObject.c[0]; //这里的顺序和计算机系统的小端或大端有关,这里为小端
	*(buff + 1) = uObject.c[1];
	*(buff + 2) = uObject.c[2];
	*(buff + 3) = uObject.c[3];
}
//程序入口函数
void main()
{
    char buffC1[4];
	Test(buffC1,-20);
	int testBuffN1 = buffC1[0];      //与Test函数中的顺序对应
	int testBuffN2 = buffC1[1];
	int testBuffN3 = buffC1[2];
	int testBuffN4 = buffC1[3];
	MyUnion u;
	u.c[0] = testBuffN1;
	u.c[1] = testBuffN2;
	u.c[2] = testBuffN3;
	u.c[3] = testBuffN4;
	cout << u.n<< endl;     //输出结果为-20
	getchar();
}	

无符号整型为16位,但当整数本身为负数时,转换为它的补码,如
unsigned int test1 = -2; //结果为4294967294
int test2 = test1; //结果为-2

//测试CString类的Format、atoi、无符号整型的负数结果
int testMarkN = -2;
CString strTestMak;
strTestMak.Format("%d",testMarkN); //结果为-2,只不过是字符串格式

CString strTestMak="-2";
                                                                                                                                                                                                        
int testMarkN = atoi(strTestMak);  //结果为-2,只不过是整型格式

CString strTestMak="-2";
unsigned int testMarkN = atoi(strTestMak); //结果为-2的补码,因为是32位整型,所以这里为4294967294

猜你喜欢

转载自blog.csdn.net/fazstyle/article/details/87955285