I’m trying to read the bitmap header. I have defined the following struct:
typedef struct {
char magic[2];
char size[4];
char reserved[4];
char offset[4];
char dibbytes[4];
char width[4];
char height[4];
char colorplanes[2];
char bpp[2];
char rawsize[4];
char hor_res[4];
char ver_res[4];
char colors[4];
char important[4];
} bmp_t;
And I open a bitmap image with this function:
void open(char * filename) {
long filesize;
char * buffer;
FILE * file = fopen(filename, "rb");
fseek(file, 0, SEEK_END);
filesize = ftell(file);
rewind(file);
buffer = (char *) malloc(sizeof(char) * filesize);
fread(buffer, 1, filesize, file);
bmp_t * bmp = (bmp_t *) buffer;
printf("Size in hex: %02x %02x %02x %02x\n", bmp->size[0], bmp->size[1], bmp->size[2], bmp->size[3]);
fclose(file);
}
To test this, I made a new bitmap, width = 1000 pixels, height = 3 pixels. The filesize is 9054 bytes. However, the output of my program is:
Size in hex: 5e 23 00 00
That’s a bit strange because 0x5e23 reversed is 0x235e, which is 9054 in decimal (the correct filesize). So the values are saved in reverse. For example, if I make a 1000×1000 bitmap, I should get a filesize of 3000054 in decimal, but I get 0xf6c62d. And the reverse, 0x2dc6f6, is 3000054 (again, the correct filesize).
So I thought I could just sprintf the string in reverse and then use atoi to convert it to int:
sprintf(bmp->size, "%c%c%c%c", bmp->size[3], bmp->size[2], bmp->size[1], bmp->size[0]);
printf("Size reversed: %02x %02x %02x %02x\n", bmp->size[0] & 0xFF, bmp->size[1] & 0xFF, bmp->size[2] & 0xFF, bmp->size[3] & 0xFF);
int size = atoi(bmp->size);`
printf("Size: %d\n", size);
For the image I get the following result:
Size reversed: 00 00 23 5e
Size: 0
So the sprintf is working great, my string is reversed and 0x235e is the correct answer. But the atoi doesn’t work on the string, and I don’t know why. Besides that, I think this method of printing a reverse string is a very strange way of reading the values.
What am I doing wrong here and what is the correct way of doing this? Thanks in advance.
Update!
Turns out it is an endianness problem. But how should I read it then? I just want to get an integer with the filesize (or width, height, anything).
This happens because everything in memory is saved in reversed order, at least on little endian machines (x86s fall in this category). Check here for details about endianness and here if you want to know why little endian is used.