[Solved] How a fread function work? [closed]


To print all bytes in an int? Remember that an int is 32-bit, which is four bytes. Reading it into a char buffer makes it easier to access those four bytes in the int.

Edit: Little explanation of the int type…

Lets say you have an int:

int someIntValue = 0x12345678;

This is stored in 32 bits in the memory. As a single byte (char) is 8 bits, there are four bytes to an int. Each byte in the int can be accessed by using a char array or pointer:

char *someCharPointer = (char *) &someIntValue;

Now you can access those four separate bytes, and see their values:

for (int i = 0; i < sizeof(int); i++)
    printf("someCharPointer[%d] = 0x%02x\n", i, someCharPointer[i]);

The above will print (on a little-endian machine such as x86):

someCharPointer[0] = 0x78
someCharPointer[1] = 0x56
someCharPointer[2] = 0x34
someCharPointer[3] = 0x12

If you now change someIntValue to the number 1

someIntValue = 1;

and print it out again, you will see this result:

someCharPointer[0] = 0x00
someCharPointer[1] = 0x00
someCharPointer[2] = 0x00
someCharPointer[3] = 0x01

Memory layout of an int

If you have a variable of type int stored in memory with the value 0x12345678, it’s stored like this:

   8 bits
,----^---.
|        |

+--------+--------+--------+--------+
|00111000|01010110|00110100|00010010|
+--------+--------+--------+--------+

|                                   |
`-----------------v-----------------'
                  |
               32 bits

This int is the same as the four bytes (or char) 0x78, 0x56, 0x34 and 0x12.

However if we change the int to the number 1 then it’s stored like this:

   8 bits
,----^---.
|        |

+--------+--------+--------+--------+
|00000000|00000000|00000000|00000001|
+--------+--------+--------+--------+

|                                   |
`-----------------v-----------------'
                  |
               32 bits

This int is the same as the four bytes (or char) 0x00, 0x00, 0x00 and 0x01.

So now you hopefully can see how reading as an int and printing as char will display a different result from reading and int and printing it as an int.

8

solved How a fread function work? [closed]