sprintf的格式化数据的时候,unsigned int 型%d打印为负数的解决办法

  • Post author:
  • Post category:其他


#include "string.h"
#include "stdlib.h"



void main()
{
	unsigned char num[10] = {0};

	 memset(num, 0, 10);
	 sprintf(num,"%d",(unsigned char)(0xFF));
	 printf("%s\n",num);
	 sprintf(num,"%d",(signed char)(0xFF));
	 printf("%s\n",num);
	 sprintf(num,"%d",(unsigned short)(0xFFFF));
	 printf("%s\n",num);
	 sprintf(num,"%d",(signed short)(0xFFFF));
	 printf("%s\n",num);
	 sprintf(num,"%u",(unsigned int)(0xFFFFFFFF));
	 printf("%s\n",num);
	 sprintf(num,"%d",(unsigned int)(0xFFFFFFFF));
	 printf("%s\n",num);
	 sprintf(num,"%d",(signed int)(0xFFFFFFFF));
     printf("%s\n",num);
}

编译结果:

255
-1
65535
-1
4294967295
-1
-1
Press any key to continue

%ld,%d,%u都是格式说明符中的类型。它的作用是将输入或者输出的数据按照格式说明符指定的格式进行输入或者输出。

(1)%ld表示数据按十进制有符号长型整数输入或输出。

(2)%d表示数据按十进制有符号整型数输入或输出。

(3)%u表示数据按十进制

无符号整型

数输入或输出。

即:

改sprintf(num,”%d”,(unsigned int)(0xFFFFFFFF)); 为:

sprintf(num,”%u”,(unsigned int)(0xFFFFFFFF));

注意点:

char / short  int/……,不同的编译软件,编译的结果不一样,keil 默认的是unsigned char /unsigned short int

VC6默认的是signed char / signed short int/…



版权声明:本文为happygrilclh原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。