为什么C打印我的十六进制值不正确?

Cea*_*sta 9 c

所以我对C来说是一个新手,我很想知道为什么我会得到这种不寻常的行为.

我一次读取16位文件,然后按如下方式打印出来.

#include <stdio.h>

#define endian(hex) (((hex & 0x00ff) << 8) + ((hex & 0xff00) >> 8))

int main(int argc, char *argv[])
 {
  const int SIZE = 2;
  const int NMEMB = 1;
  FILE *ifp; //input file pointe
  FILE *ofp; // output file pointer

  int i;
  short hex;
  for (i = 2; i < argc; i++)
   {
    // Reads the header and stores the bits
    ifp = fopen(argv[i], "r");
    if (!ifp) return 1;
    while (fread(&hex, SIZE, NMEMB, ifp))
     {
      printf("\n%x", hex);
      printf("\n%x", endian(hex)); // this prints what I expect
      printf("\n%x", hex);
      hex = endian(hex);
      printf("\n%x", hex);
     }   
   }
 }
Run Code Online (Sandbox Code Playgroud)

结果看起来像这样:

ffffdeca
cade // expected
ffffdeca
ffffcade
0
0 // expected
0
0
600
6 // expected
600
6
Run Code Online (Sandbox Code Playgroud)

任何人都可以向我解释为什么每个块中的最后一行不会打印与第二行相同的值?

tim*_*qiu 18

%x格式字符串中的占位符将相应的参数解释为unsigned int.

要将参数打印为short,请h向占位符添加长度修改器:

printf("%hx", hex);
Run Code Online (Sandbox Code Playgroud)

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


Mys*_*ial 10

这是由于整数类型提升.

shorts被隐含地提升为int.(这里是32位)所以这些是在这种情况下的符号扩展促销.

因此,您printf()正在打印出完整32位的十六进制数字int.

当你的short值为负数时,符号扩展将用前导符号填充前16位,因此你得到的ffffcade不是cade.


这条线的原因:

printf("\n%x", endian(hex));
Run Code Online (Sandbox Code Playgroud)

似乎工作是因为你的宏隐含地摆脱了高16位.