I have the example :
unsigned int dwColor = 0xAABBCCFF; //Light blue color
-
And its parameters from left to right are : “alpha, red, green, blue”; each parameter requires two hexadecimal values.
-
The maximum value of each parameter is 255; lowest : 0
And, how to extract then convert all parameters of a DWORD color to decimals?
I like the value range “0.00 -> 1.00”.
For example :
float alpha = convert_to_decimal(0xAA); //It gives 0.666f
float red = convert_to_decimal(0xBB); //It gives 0.733f
float green = convert_to_decimal(0xCC); //It gives 0.800f
float blue = convert_to_decimal(0xFF); //It gives 1.000f
EDIT : I’ve just seen union, but the answerer says it’s UB (Undefined Behaviour). Does anyone know the better solution? 🙂
I usually use an
union:If you need to treat it as a float value:
EDIT:
As mentioned in the comments below, this use of
unionis Undefined Behaviour (UB), see this question from Luchian Grigore.EDIT 2:
So, another way to break a
DWORDinto components avoiding theunionis using some bitwise magic:But I do not advise the macro solution, I think is better to use a function:
How it works? Lets supose we call
get_component(0xAABBCCFF, 0):Lets supose we call
get_component(0xAABBCCFF, 2):Warning! not all color formats will match that pattern!
But IMHO, the neater solution is to combine the function with an enum, since we’re working with a limited pack of values for the index:
The last approach ensures that the bitwise operations will only be performed if the input parameters are valid, this would be an example of usage:
And here is a live demo.