Why does C print my hex values incorrectly?

后端 未结 3 1893
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-17 21:28

So I\'m a bit of a newbie to C and I am curious to figure out why I am getting this unusual behavior.

I am reading a file 16 bits at a time and just printing them ou

相关标签:
3条回答
  • 2020-12-17 22:20

    This 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 ffffcade rather than cade.


    The reason why this line:

    printf("\n%x", endian(hex));
    

    seems to work is because your macro is implicitly getting rid of the upper 16-bits.

    0 讨论(0)
  • 2020-12-17 22:22

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

    http://en.wikipedia.org/wiki/Printf_format_string#Format_placeholders

    0 讨论(0)
  • 2020-12-17 22:24

    You have implicitly declared hex as a signed value (to make it unsigned write unsigned short hex) so that any value over 0x8FFF is considered to be negative. When printf displays it as a 32-bit int value it is sign-extended with ones, causing the leading Fs. When you print the return value of endian before truncating it by assigning it to hex the full 32 bits are available and printed correctly.

    0 讨论(0)
提交回复
热议问题