When formatting data in sprintf, unsigned int type% d is printed as a negative solution

#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);
}

Compilation result:

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

 

% ld,% d,% u are all types in the format specifier. Its function is to input or output the input or output data according to the format specified by the format specifier.

(1)% ld indicates that the data is input or output as a decimal signed long integer.

(2)% d indicates that the data is input or output as a decimal signed integer.

(3)% u indicates that the data is input or output as a decimal unsigned integer .

 

which is:

Change sprintf (num, "% d", (unsigned int) (0xFFFFFFFF)); to:

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

Published 105 original articles · Like 30 · Visits 160,000+

Guess you like

Origin blog.csdn.net/happygrilclh/article/details/105657289