簡體   English   中英

使用Big-Endian問題在C ++中加載位圖

[英]Loading Bitmap in C++ with Big-Endian issues

我目前正在使用以下代碼在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上運行,並且從位圖標題中拉出錯誤的Width和Height。 我認為這與Little Endian(常規PC)和Big Endian(PowerPC)有關。

我應該如何在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開發環境,不知道在那里使用了什么。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM