The following program
short b =-10;
printf("%x %d",b,sizeof(b));
outputs (on vs 2008)
FFFFFFF6 2
Why not
FFF6 2
The same is with signed char.
It is due to integer type-promotion.
Your shorts are being implicitly promoted to int. (which is 32-bits here) So these are sign-extension promotions in this case.
Therefore, your printf() is printing out the hexadecimal digits of the full 32-bit int.
When your short value is negative, the sign-extension will fill the top 16 bits with ones, thus you get fffffff6 rather than fff6.
The placeholder %x in the format string interprets the corresponding parameter as unsigned int.
To print the parameter as short, add a length modifier h to the placeholder:
printf("%hx", hex);
Here h Indicates that the conversion will be one of dioux X or n and the next pointer is a pointer to a short int or unsigned short int (rather than int).
codepad link: http://codepad.org/aX2MzY0o
see this : http://en.wikipedia.org/wiki/Printf_format_string#Format_placeholders
Because it is promoted to the int data type. The expression sizeof(type) * CHAR_BIT
evaluates to the number of bits enough to contain required ranges.
Also note that short may be narrower, but may also be the same width as, int. It is always guaranteed that int is equal to or bigger than short int.
CPU short int
8 bit 16 16
16 bit 16 16
32 bit 16 32
64 bit 16 32
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.