在C++中加载位图时出现Big Endian问题

Loading Bitmap in C++ with Big-Endian issues

本文关键字:Big Endian 问题 C++ 加载 位图      更新时间:2023-10-16

我目前正在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数据吗?

您可以这样做(它应该适用于big-endian或little-endian架构):

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开发环境来了解那里使用了什么。