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.
Looks like you are missing the terminology Endianess. Many systems save their words (4-bytes in a 32-bit system) in "Little Endian" order - that is "little end" first. This means the least significant byte (LSB) is first (lowest address), and it goes up from there. That's why 2 is first (lowest address, LSB) and 1 is second, and then the 0s of the most significant bytes. Endianess is only important when you are manipulating byte level data, but then it is very important to know which endianess your system uses.
Alignment has nothing to do with it - single bytes are always read the same in all systems, like we usually write numbers - LSB on the right.