Why does C print my hex values incorrectly?

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

提交回复
热议问题