Search code examples
cgccrgbdata-conversionrgba

C - RGBA Conversion Not Returning The Desired RGB Result


Okay, I have a method that I am having a difficult time with returning the desired results. So I made a test result, and it is returning a result that I was not expecting.

Here is an example -->

int color = 0x00FFFF00;

return 0xFF & (color >> 24) | 0xFF & (color >> 16) | 0xFF & (color >> 8);

From what I know, this should return:

0x00FFFF

However, it actually returns:

0x0000FF

Can someone please explain what is happening? I would also like to know how I could properly convert the 32-bit RGBA integer to the 24-bit RGB integer, thank you.


Solution

  • Try this:

    #include <stdio.h>
    int main() {
    
            unsigned int x = 0x00FFFF00;
            printf("0%8.8x", (x >> 8) & 0x00FFFFFF);
    }
    
    $ cc -o shft shft.c
    $ ./shft
    0x0000ffff
    

    It's better if you make color an unsigned int, otherwise you can get the sign bit shifted in from the left, but in this case we're masking off the shifted in bytes, but be careful of that.