简体   繁体   中英

How to unpack uint32_t colour in c++

I currently have a uint32_t variable that stores the rgb colours of a pixel. It looks like:

uint32_t colour = (255<<24) + (int(red)<<16) + (int(green)<<8) + int(blue);

where the variables red green and blue are values up to 255. I would like to take this uint32_t and unpack it so I can separate out the individual colour values. I would then like to store these individual values in an array

  color[0] = ; // red integer between 0 and 255
  color[1] = ; // green integer between 0 and 255
  color[2] = ; // blue integer between 0 and 255

Thanks for your help.

You'd need to mask out the relevant parts and then shift it to be in the correct range.

Here's some code:

constexpr uint32_t blue_offset{ 0x00 };
constexpr uint32_t green_offset{ 0x08 }; // 8 decimal
constexpr uint32_t red_offset{ 0x10 }; // 16 decimal
constexpr uint32_t alpha_offset{ 0x20 }; // 24 decimal

constexpr uint32_t byte_mask{ 0xFF };
constexpr uint32_t blue_mask{ byte_mask << blue_offset };
constexpr uint32_t green_mask{ byte_mask << green_offset };
constexpr uint32_t red_mask{ byte_mask << red_offset };
constexpr uint32_t alpha_mask{ byte_mask << alpha_offset };

color[0] = (colour & red_mask >> red_offset) & byte_mask;
color[1] = (colour & green_mask >> green_offset) & byte_mask;
color[2] = (colour & blue_mask >> blue_offset) & byte_mask;

See this tutorial for a great explanation. There's an example with RGB colours down the page.

Unpacking can be done with:

 color[0] = (colour >> 16) & 0xff; // red
 color[1] = (colour >> 8) & 0xff; // green
 color[2] = colour  & 0xff; // blue

Note that you could also use a struct to directly unpack provided you know the endianess of the machine your run on eg:

int main()
{

    char red = 25;
    char green = 57;
    char blue = 23;

    unsigned int colour = (255<<24) + (int(red)<<16) + (int(green)<<8) + int(blue);

    struct s_rgb
    {
        unsigned int b:8;
        unsigned int g:8;
        unsigned int r:8;
        unsigned int alpha:8;
    };

    s_rgb rgb = *(s_rgb*)&colour;
    cout <<std::dec<< "r:"<< (int)rgb.r << " g:"<< (int)rgb.g << " b:"<< (int)rgb.b << endl;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM