1
\$\begingroup\$

I have two pixes stored in a 32 bit unsigned integer (4 bytes per pixel, using SDL's types for convenience):

Uint32 pixel1;        // Source pixel, format: SDL_PIXELFORMAT_BGRA8888
Uint32 pixel2_format; // Format of the pixel2 (can change)
Uint32 pixel2;        // Destination pixel

How can I convert the format from pixel1 to pixel2?

\$\endgroup\$
0

2 Answers 2

1
\$\begingroup\$

If I understand it right, you are asking how to extract bites of one bitmask and set it on the other, for example :

const uint mask = 0x000000FF; //single color mask
const uint aOff = 3 * 8; //offsets of colors from the end for ARGB
const uint rOff = 2 * 8;
const uint gOff = 1 * 8;
const uint bOff = 0 * 8;

uint pixel1 = 0xFFFF0000; //red in ARGB
uint pixel2 = 0x0;
pixel2 |= ((pixel1 & (mask << bOff)) >> bOff) << (3 * 8);//set b
pixel2 |= ((pixel1 & (mask << gOff)) >> gOff) << (2 * 8);//set g
pixel2 |= ((pixel1 & (mask << rOff)) >> rOff) << (1 * 8);//set r
pixel2 |= ((pixel1 & (mask << aOff)) >> aOff) << (0 * 8);//set a

first, you create appropriate mask (mask << bOff) by shifting single color mask to correct position (alternatively, because it is static value tied to source pixel format so you can pre-compute it), then you extract all bits of the color channel by pixel1 & mask and shift them to get the value value >> bOff. After that you shift the value to its correct position in BGRA8888 format value << (pos * 8) and last you or it with zeroed BGRA8888 pixed pixel2 |= shiftedValue.
You can skip some shifting if you know the formats in advance and hardcode it.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ Don't you need to bitwise OR the components of the pixel? Instead of AND? \$\endgroup\$
    – Xriuk
    Commented Jan 22, 2016 at 9:19
  • \$\begingroup\$ @Xriuk yes, sorry there was a mistake, last operation should be OR. (alternatively, setting default value of pixel2 to ones - 0xFFFFFFFF would also work) \$\endgroup\$
    – wondra
    Commented Jan 23, 2016 at 12:08
0
\$\begingroup\$

Ok, I had to add this answer because I found something on my own:
Basically there is this function SDL_ConvertPixels() hidden in the wiki and it's located inside SDL_surface.h header and not inside SDL_pixels.h (mystery...). This function converts pixels from any supported PixelFormat to another one.

Plus, a suggestion for everybody: When working with bits, remember to check the endianess of your machine or you'll get pixels with inverted colors (like I did...)!

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .