1
votes

I am writting a C++ command line application that will apply the Haar transform to the pixels of a bmp image. I have successfully been able to extract the header information and determine the byte array size for the pixels. After filling a char[pixelHeight][rowSizeInBytes] with the pixel data from the file, I am reading each pixel (24 bits for the bmp I'm using) into a vector. It is working on my machine but I would like to know if my implementation for converting the char array representing a pixel into an unsigned int is safe and/or the idiomatic C++ way. I am assuming a little endian architecture.

unsigned char pixelData[infoHeader->pixelHeight][rowSize];
fseek(pFile, basicHeader->pixelDataOffset, SEEK_SET);
fread(&pixelData, pixelArraySize, 1, pFile);

for(int row = 0; row < infoHeader->pixelHeight; row++)
{
    for(int i = 0; i < rowSize; i = i + 3)
    {
        unsigned char blue = pixelData[row][i];
        unsigned char green = pixelData[row][i + 1];
        unsigned char red = pixelData[row][i + 2];

        char vals[4];
        vals[0] = blue;
        vals[1] = green;
        vals[2] = red;
        vals[3] = '\0';

        unsigned int pixelVal = *((unsigned int *)vals);

        pixelVec.push_back(pixelVal);
    }
}
1
Why do you want a vector of unsigned integers rather than a vector of structures each containing three color values?David Schwartz
When You say I am assuming little endian architecture, does that mean you will neverr run this on a big endian system?DanChianucci
David Schwartz, The reason I'm storing them as scalar values is so I can apply the Haar transform to the array. My understanding is that the transform can only be applied to a series of scalars but I might be wrong on this. This is part of an exercise from this blog post: knowing.net/index.php/2006/06/16/… . I thought I'd try it out with C++WSkinner

1 Answers

4
votes

No, this is unidiomatic. You should code what you mean rather than relying on the endianness of the system. For example:

 unsigned int pixelVal = static_cast<unsigned int>(blue) |
     (static_cast<unsigned int>(green) << 8) |
     (static_cast<unsigned int>(red) << 16);

This assumes your intention was to get a vector with specific values for unsigned integers. If your intention was to get a vector with specific bytes, you should use a vector of byte-sized structures, not unsigned integers.