Halfway between your proposed solution (OP) and Patrick's solution, it looks pretty neat:
Color colors[5]={ 0xAARRGGBB,...}; unsigned long sum1=0,sum2=0; for (int i=0;i<5;i++) { sum1+= colors[i] &0x00FF00FF; // 0x00RR00BB sum2+=(colors[i]>>8)&0x00FF00FF; // 0x00AA00GG } unsigned long output=0; output|=(((sum1&0xFFFF)/5)&0xFF); output|=(((sum2&0xFFFF)/5)&0xFF)<<8; sum1>>=16;sum2>>=16; // and now the top halves output|=(((sum1&0xFFFF)/5)&0xFF)<<16; output|=(((sum2&0xFFFF)/5)&0xFF)<<24;
I donβt think you can really divide sum1 / sum2 by 5, because the bits from the upper half will spill ...
If the approximation were valid, you could try multiplying by something like 0.1875 (0.125 + 0.0625) (this means: multiply by 3 and shift down by 4 places. This can be done using bitmasking and leaving). The problem is that 0.2 has a crappy binary representation, so multiplying it is an ass.
As always, accuracy or speed. Your choice.
source share