0

I wanted to display the highest and lowest "short" values as hexadecimal numbers (using a Windows environment, mingw64 compiler):

printf("largest %x and smallest %x",SHRT_MAX,SHRT_MIN)

The output was as expecteded for the max number -> 7fff but for the min number the result is -> ffff 8000

Does anyone know why the min number is shown as a 4 byte number.

Thanks for your help, Bert

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Bert
  • 57
  • 6
  • `"%x"` expects an unsigned int, `SHRT_MIN` has type int. Try `printf("largest %d and smallest %d\n", SHRT_MAX, SHRT_MIN)` or `printf("largest %x and smallest -%x\n", SHRT_MAX, (unsigned)-SHRT_MIN)` – pmg Aug 05 '20 at 18:27
  • 4
    Use `%hx` instead, to say that the value is a `short`. – Some programmer dude Aug 05 '20 at 18:32
  • 4
    `%hx` would be appropriate for `SHRT_MAX`, but still non-conforming for `SHRT_MIN`, because of the signedness mismatch. One could combine that with a cast to `unsigned short` -- that conforms, and it will yield the (presumable) expected result on two's complement systems. – John Bollinger Aug 05 '20 at 18:33
  • Thank you very much for the answers. The %hx formatting solved the problem. – Bert Aug 05 '20 at 18:41

1 Answers1

0

Here you are

#include <stdio.h>
#include <limits.h>

int main(void) 
{
    printf( "largest %#hx and smallest %#hx\n", SHRT_MAX, SHRT_MIN );
    
    return 0;
}

The program output is

largest 0x7fff and smallest 0x8000

That is you need to use the length modifier h. Otherwise due to the integer promotions the values are outputted as objects of the type int.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • In the comments the point was made that `%hx` is non-conforming for `SHRT_MIN`. Is that not so? (I think the purpose of the `#` specifier is to affect an _alternate form_, but has no other effect.) – ryyker Aug 05 '20 at 19:40
  • @ryyker It is a hex representation. Neither sign is used. – Vlad from Moscow Aug 05 '20 at 21:52