Other color reduction formulas
In our example, the color reduction is achieved by taking advantage of an integer division that floors the division result to the nearest lower integer as follows:
data[i]= (data[i]/div)*div + div/2;
The reduced color could have also been computed using the modulo operator that brings us to the nearest multiple of div (the per-channel reduction factor) as follows:
data[i]= data[i] - data[i]%div + div/2;
Another option would be to use bitwise operators. Indeed, if we restrict the reduction factor to a power of 2, that is, div=pow(2,n), then masking the first n bits of the pixel value would give us the nearest lower multiple of div. This mask would be computed by a simple bit shift as follows:
// mask used to round the pixel value uchar mask= 0xFF<<n; // e.g. for div=16, mask= 0xF0
The color reduction would be given by the following code:
*data &= mask; // masking *data++ += div>>1; // add div/2
In general, bitwise operations might lead to very efficient code, so they could constitute a powerful alternative when efficiency is a requirement.