gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 16:50:53 26 4
gpt4 key购买 nike

所以我是 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);
}
}
}

结果看起来像这样:

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

谁能向我解释为什么每个 block 中的最后行打印的值与第二行不相同?

最佳答案

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

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

printf("%hx", hex);

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

关于c - 为什么 C 不正确地打印我的十六进制值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8441257/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com