Question

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

Was it helpful?

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.

OTHER TIPS

UINT32 ColorValue (float r, float g, float b, float a) throw(int)
{
    if      ((r<0) || (1<r)) throw(1);  // Argument range check if needed
    else if ((g<0) || (1<g)) throw(2);
    else if ((b<0) || (1<b)) throw(3);
    else if ((a<0) || (1<a)) throw(4);
    return  (static_cast<UINT32>(round(a * static_cast<float>(0xFF))) << 24) |
            (static_cast<UINT32>(round(b * static_cast<float>(0xFF))) << 16) |
            (static_cast<UINT32>(round(g * static_cast<float>(0xFF))) << 8)  |
            (static_cast<UINT32>(round(r * static_cast<float>(0xFF))));
}

This might be a solution to your problem. You can remove the range checking part for higher performance if it is guarantied that the arguments will always be in the valid range.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top