C语言中有符号数和无符号数的认识

程序中运用到 电压、电流两个参数,两个都有正负的情况,现在通过下列情景来认识有符号数和无符号数的运用:
1.Ad采样值经过校准得出的值为float类型,然后强制转换成int16类型;
2.转换成的int16类型会经过放大10倍;
3.然后该int16类型的数会用来和某些int16类型的数据进行比较判断;
4.最后该int16类型会强制转换成uint16类型通过总线送出去;

#include 
	 
int main()
{
	float volt1 = -1.0;
	float curr1 = 2.0;
	
	signed short int volt2;
    signed short int curr2;

   	signed short int volt3;
   	signed short int curr3;

   	signed short int volt4 = -9;
   	signed short int curr4 = 23;

   	unsigned short int volt5;
   	unsigned short int curr5;


	volt2 = (signed short int)volt1;							// float 转换成 signed short int
	curr2 = (signed short int)curr1;
	
	volt3 = volt2 * 10;											// signed short int 放大10倍
	curr3 = curr2 * 10;

	
	printf("(float)volt1 = %.1f\n",volt1);
	printf("(float)curr1 = %.1f\n",curr1);
	printf("\n");
	printf("(signed short int)volt2 = %#X\n",volt2);			// %x结果是小写
	printf("(signed short int)curr2 = %#X\n",curr2);			// %X结果是大写
	printf("\n");
	printf("(magn10 signed short int)volt3 = %#X\n",volt3);
	printf("(magn10 signed short int)curr3 = %#X\n",curr3);
	printf("\n");

	if (volt3 > volt4)											// 有符号数之间的判断
	{
		printf("(magn10 signed short int)volt3 = %#X\n",volt3);
	}
	else 
	{
		printf("(signed short int)volt4 = %#X\n",volt4);
	}

	if (curr3 > curr4)
	{
		printf("(magn10 signed short int)curr3 = %#X\n",curr3);
	}
	else 
	{
		printf("(signed short int)curr4 = %#X\n",curr4);
	}

	volt5 = (unsigned short int)volt3;							// signed short int 转换成 unsigned short int
	curr5 = (unsigned short int)curr3;
	printf("\n");
	printf("(unsigned short int)volt5 = %#X\n",volt5);
	printf("(unsigned short int)curr5 = %#X\n",curr5);
	printf("\n");
	printf("(magn10 signed short int)volt3 = %#X\n",volt3);
	printf("(magn10 signed short int)curr3 = %#X\n",curr3);
	printf("\n");
	printf("sizeof(volt3) = %d\n",sizeof(volt3));				// 确认signed short int和unsigned short int分别占用几个字节
	printf("sizeof(curr3) = %d\n",sizeof(curr3));				// 确认signed short int和unsigned short int分别占用几个字节
	printf("sizeof(volt5) = %d\n",sizeof(volt5));
	printf("sizeof(curr5) = %d\n",sizeof(curr5));
	printf("\n");
	
	return 0;
}

运行结果如上所示:C语言中有符号数和无符号数的认识_第1张图片
有个问题不明白:
为什么:unsigned short int 和signed short int都占用两个字节,但是volt5显示为2个字节,volt3显示4个字节?

你可能感兴趣的:(C#)