使用Big-Endian问题在C ++中加载位图

时间:2015-11-10 14:19:06

标签: c++ bitmap endianness

我目前正在使用以下代码在Visual Studio中读取位图:

    unsigned char* imageIO::readBMP(char* filename) {
    FILE* f = fopen(filename, "rb");
    if (f == NULL)
    {
        printf("%s \n", "File Not Loaded");
    }

    unsigned char info[54];
    fread(info, sizeof(unsigned char), 54, f); //read the 54-byte header

    //extract image height and width from header
    imageWidth = *(int*)&info[18];
    imageHeight = *(int*)&info[22];

    imageBytes = 3;
    size = imageWidth * imageHeight * imageBytes;

    unsigned char* readData = new unsigned char[size]; //allocate 3 byte per pixel
    fread(readData, sizeof(unsigned char), size, f); //read the rest of the data at once
    fclose(f);

    return readData;
}

但是我试图让这段代码在PowerPC上工作,它从位图头中拉出错误的宽度和高度。我认为这与Little Endian(普通PC)和Big Endian(PowerPC)有关。

如何在Big Endian机器上读取位图?

我可以翻转Little Endian数据吗?

1 个答案:

答案 0 :(得分:0)

你可以做这样的事情(它应该适用于大端或小端架构):

unsigned int getIntLE(const unsigned char *p) {
#if LITTLE_ENDIAN
    return *(unsigned int *)p;
#else
    return ((unsigned int)p[3] << 24) | 
           ((unsigned int)p[2] << 16) | 
           ((unsigned int)p[1] << 8) | 
           p[0];
#endif
}

// ...

imageWidth = getIntLE(&info[18]);
imageHeight = getIntLE(&info[22]);

请注意,您需要定义LITTLE_ENDIAN或使用Visual Studio预定义的内容。我没有方便的Windows开发环境来了解那里使用的内容。