为什么C打印我的十六进制值不正确? [英] Why does C print my hex values incorrectly?

查看:100
本文介绍了为什么C打印我的十六进制值不正确?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有点新手到C和我好奇地找出为什么我收到此异常行为。

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

我读一个文件16位的时间和刚打印出来如下:

I am reading a file 16 bits at a time and just printing them out as follows.

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

结果是这个样子:

The results look something like this:

ffffdeca
cade // expected
ffffdeca
ffffcade
0
0 // expected
0
0
600
6 // expected
600
6

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

Can anyone explain to me why the last line in each block doesn't print the same value as the second?

推荐答案

这是因为整型推广。

短裤正在暗中提升到 INT 。 (这是这里32位),所以这些都是在这种情况下,符号扩展优惠

Your shorts are being implicitly promoted to int. (which is 32-bits here) So these are sign-extension promotions in this case.

因此​​,你的的printf()正在打印出完整的32位的十六进制数字 INT

Therefore, your printf() is printing out the hexadecimal digits of the full 32-bit int.

当你的价值为负,符号扩展将填补与那些前16位,从而可以实现 ffffcade ,而不是凯德

When your short value is negative, the sign-extension will fill the top 16 bits with ones, thus you get ffffcade rather than cade.

之所以这样行:

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

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

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

这篇关于为什么C打印我的十六进制值不正确?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆