Why is Fread reading unsigned-int in reverse order?

旧时模样 提交于 2021-02-11 14:39:46

问题


My binary file contains

0400 0000 0000 0000 0400 0000 0000 0000

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

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

My understanding is the first four bytes are 0400 0000

EDIT: Code and the wordings of the question


回答1:


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

it is exactely like if you do

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)

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

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


Update after question editing

My binary file contains

0400 0000 0000 0000 0400 0000 0000 00000000 0000 0000

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

a character is on 8 bits, not on 16

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

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



来源:https://stackoverflow.com/questions/54856419/why-is-fread-reading-unsigned-int-in-reverse-order

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!