问题
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