I would like to multiply two colors whose components are byte
but I'm running into inconsistent results.
When components are float
it's exact and easy:
float a = 1.0f;
float b = 1.0f;
float c = a * b;
When components are byte
, I vaguely remember there's some bit-shifting, however my formula is clearly missing something:
byte a = 255;
byte b = 255;
byte c = (byte)((a * b) >> 8);
// 255 * 255 = 65025 then 65025 >> 8 = 254
// obviously, adding 1 to the result is just wrong
Note:
I can't use a Color
type from popular frameworks such as Forms or WPF, as my project acts as an abstraction layer that is to be re-used from different frameworks.
Question:
What is the right algorithm for for multiplying byte
colors using bit-shifts ?
Harold's comment worked for me:
(byte)((a * b + 0xFF) >> 8)
I am reposting his comment as an answer to make his solution easier to find.