Reputation:
I am reading the header of a bmp file. My system and bmp file values are both in little endian format. So I read as below:
uint32_t fileSize;
fread(&fileSize,1,4,bmpFile);
In bmp file, these bytes are ordered as: ... 36 04 01 00 ... The resulting value of the fileSize is 66614 which is: 0x00010436. I get the correct value and there is no problem.
However something bothers me. Does this code work similarly for a big endian machine or does fread() behave differently and I get 0x36040100 incorrectly?
Upvotes: 5
Views: 394
Reputation: 12658
fread()
in your program reads 36
04
01
00
bytes to int32 fileSize
variable. Since your CPU is little endian which actually reads bytes from left to right as 00
01
04
36
rather right to left. Therefore when you read a binary file you must convert form the file format endianess to your system CPU endianess.
Upvotes: 1
Reputation: 50775
fread
reads the data "as is" into memory, therefore your code will definitely behave differently on a big endian CPU than on a little endian CPU.
In other words fread
does not know that you are reading a uint32_t
. All fread
knows is that you want to read 4 bytes to the memory location where the fileSize
variable lives.
Upvotes: 4