Hi, this is probably really easy, but..
how do I best do a fast, accurate integer scaling (0.0 - 1.0) of 2 unsigned chars (8 bit values)?
[Note: this is the same problem as doing accurate alpha-blending. But it is also useful in other areas, e.g. audio.]
e.g.
a = 100; // test number
b = 250; // scale factor 0 - 255, which should correspond to a 0.0 to 1.0 factor
result = (a * b) / 255;
However in this case the divide by a non-magic number (2, 4, 8, 16, etc) is presumably not as good as dividing by 256 which can be a bitshift? Although perhaps these days in most CPUs this is not an issue as memory bandwidth is more important?
And finally, what is the *best* way of doing this, allowing floating point stuff (and perhaps SIMD, maybe there is an instruction for it?).
*edit*
Variations I've seen:
1) Just divide by 256 (the bitshift)
(and ignore the fact that 255 x 255 will come out as 254 as the result)
Pros: Works fast
Cons: Might be ok in many uses but isn't accurate.
2) result = (a * (b+1)) / 256;
Pros: Should be almost as fast as the above.
when b = 0
e.g. 255 * 1 = 255,
255 / 256 = 0 CORRECT
when b = 255
255 * 256 = 65280
65280 / 256 = 255 CORRECT
Cons: Are there some cases where this gives different results than the 'true' result? Not sure
*/edit*