为什么Fread以相反的顺序读取unsigned-int? [英] Why is Fread reading unsigned-int in reverse order?

查看:79
本文介绍了为什么Fread以相反的顺序读取unsigned-int?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的二进制文件包含

0400 0000 0000 0000 0400 0000 0000 0000

当我使用以下代码读取未签名的int中的前4个字节时 inputInteger

When I use the following code to read the first 4 bytes in an unsigned int inputInteger

FILE *inputFile;
inputFile = fopen("./Debug/rnd_2", "rb");
unsigned int inputInteger = 0;
fread(&inputInteger, sizeof(unsigned int), 1, inputFile);
fclose(inputFile);
exit(0);

我得到的是 inputInteger == 4 .考虑到位位置为 00000100 00000000 ,它应该不是1024吗?

What i get is inputInteger == 4. Should it not have been 1024 considering the bit position being 00000100 00000000?

我的理解是前四个字节是 0400 0000

My understanding is the first four bytes are 0400 0000

编辑:代码和问题的措辞

推荐答案

fread 按顺序读取字符并将它们按相同的顺序放在目标位置,因此对于同一文件,结果将不会对于小端字节序和大端字节序都是相同的,当您将结果考虑为 int

fread read the characters in order and put them in the same order in the destination, so for the same file the result will not be the same for little and big endian when you will consider back the result as an int

就跟你做的一样

char * p = (char *) &number;

p[0] = fgetc(file);
p[1] = fgetc(file);
...
p[sizeof(int) - 1] = fgetc(file);

(假设文件中有足够的字符)

(supposing there are enough characters in the file)

结果读出的数字是4.位0000 0100 0000 0000 == 1024吗?

Turns out number read is 4. Is not the bits 0000 0100 0000 0000 == 1024?

取决于您的尾数是大还是小,是1024还是64

depends if you are little or big endian, is 1024 or 64

问题编辑后更新

我的二进制文件包含

My binary file contains

0400 0000 0000 0000 0400 0000 0000 00000000 0000 0000

0400 0000 0000 0000 0400 0000 0000 00000000 0000 0000

那个时候似乎您以六进制提供值(而不是像以前那样以2为基数),所以您的意思是您的文件包含

that time it seem you give the values in hexa (not in base 2 as previously), so you mean your file contains

04 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 00 00 00

04 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 00 00

一个字符在8位上,而不是16位上

a character is on 8 bits, not on 16

  • 如果在32位上的小字节序给出4 +(0 << 8)+(0 << 16)+(0 << 24)= 4

  • if little endian on 32 bits that gives 4 + (0<<8) + (0<<16) + (0<<24) = 4

如果在32位上使用大端字节序,则得出(4<< 24)+(0<< 16)+(0<< 8)+ 0 = 16384

if big endian on 32 bits that gives (4<<24) + (0<<16) + (0<<8) + 0 = 16384

这篇关于为什么Fread以相反的顺序读取unsigned-int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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