Why does C print my hex values incorrectly?

后端 未结 3 1898
爱一瞬间的悲伤
爱一瞬间的悲伤 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.

提交回复
热议问题