Вопрос

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?

Это было полезно?

Решение

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.

Другие советы

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top