Search code examples
c++colorshexmaskbit

convert RGBA values to ABGR hexadecimal


Some functions I've been using require me to input colors in 0xAABBGGRR format [UINT32]

It would be a much more user-friendly interface if this could be accomplished with RGBA float values, ranged from 0 to 1 as they normally are.

Is there a simple way to accomplish this?

To make my question more clear,

UINT32 ColorValue(float r, float g, float b, float a) {
   // ???
}

Example: ColorValue(1,0,0,1) == 0xFF0000FF


Solution

  • Since, I presume, you are interested in learning, I'm not going to post an answer that you can just paste into your code, instead I'll explain the components you need:

    1. You need to convert a float value in the range 0..1 into an integer value 0..255. You do this by multiplying the float value with 255 and storing it in an integer.
    2. You need to "shuffle" values within an integer. This is done with the << operator, so x << y shuffles the value of x to the left by y bits.
    3. You need to combine multiple components into one integer value. You do this with the | operator. In this case, 0xFF | 0xFF0000 would become 0xFF00FF.

    The rest is just taking the lego pieces I've described above and putting them together in the right places.