2

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.

Spikatrix
  • 20,225
  • 7
  • 37
  • 83
Rohit Bohara
  • 323
  • 4
  • 14

2 Answers2

5

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 d i o u x 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

Jeegar Patel
  • 26,264
  • 51
  • 149
  • 222
  • 1
    I was *just* about to downvote because you didn't mention integer promotion - it's as if you read my mind! – Drew McGowen Aug 08 '14 at 13:15
  • @Mr. The placeholder %x in the format string interprets the corresponding parameter as unsigned int. unsigned short b=-10; printf("%x %d",b ,sizeof(b)); output FFF6 2 why unsigned short int is not been promoted to unsigned int – Rohit Bohara Aug 08 '14 at 13:57
0

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
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
  • When talking about the size of `int`, if I'm not mistaken `int` can't be larger than `long` (the same it can't be smaller than `short`). And `char` can be just about any size, but `sizeof(char)` will *always* return `1` no matter the actual size. – Some programmer dude Aug 08 '14 at 13:08
  • @JoachimPileborg:- Yes thats a valid point you added however I think OP is asking about int and short so I added only those two in my answer, or is it that I am missing something? – Rahul Tripathi Aug 08 '14 at 13:09
  • No no, you're not missing anything, I just wanted to add those for completeness. :) – Some programmer dude Aug 08 '14 at 13:30
  • @JoachimPileborg:- Ok great. Thanks for that. (Although i dont know why i received the downvote) – Rahul Tripathi Aug 08 '14 at 14:19