I got really confused while I was trying some things out with fwrite function in C.
I read through the manual of fwrite here http://www.cplusplus.com/reference/cstdio/fwrite/
It says the functions writes the array byte by byte, so I tried to write an array of integers, expecting each integer in the array be split up to 4 characters.
I thought that a bit representation of a value is right-aligned on memory. That is, 98(ascii of 'b') would be stored as
00000000 00000000 00000000 01100010
on the memory. So I expected the fwrite function to write ' ', ' ', ' ', 'b' in the txt file. Instead, it wrote 'b', ' ', ' ', ' '.
I got confused so I tested it again with pointer, hoping my knowledge about memory storage was not wrong and it was only about fwrite function. I made an integer array arr, and put (1<<8)+2, 98 in it.
I used char pointer to split each integer into four bytes. Here's the code.
#include <stdio.h>
int main()
{
int arr[5]={(1<<8)+2, 98, 'c', 'd', 'e'};
char *p = (char*)&(arr[0]);
printf("%d %d %d %d %d %d", arr[0], (int)(*p), (int)(*(p+1)), (int)(*(p+2)), (int)(*(p+3)), (int)(*(p+4)));
FILE *fp;
fp = fopen("TestFile2.txt", "a");
fwrite(arr, sizeof(char), 5, fp);
fclose(fp);
}
The program printed "258 2 1 0 0 98" on the console, and " b" was written in TestFile2 (exlcluding "s).
In my knowledge, (1<<8)+2 representation in terms of bits is
00000000 00000000 00000001 00000010 so the program should've printed 258 0 0 1 2 0.
The weird thing is that the result is not even left-aligned bit representation of the value either.
How is a value store on the memory bitwise? Is it not like what I thought it is? Or, am I missing something else here?
Any helps would be really appreciated.