Some days ago I downloaded sources of SumatraPDF and started exploring it. I found that library MuPDF сontains on interesting function, but not understand it.
static inline int fz_mul255(int a, int b) {
int x = a * b + 128;
x += x >> 8;
return x >> 8;
}
In some other sources I found another definition of mul255 function:
(a+1)*b >> 8
What is it? Help.
If it weren't for the second line (x += x >> 8
) I'd know exactly what the method does. If we remove it, for purpose of discussion:
static inline int fz_mul255(int a, int b) {
int x = a * b + 128;
// x += x >> 8;
return x >> 8;
}
The method now multiples a * b, which are fixed-point numbers with 8 fractional bits, rounding to the nearest result. Specifically, the a * b
is the multiple, the + 128
rounds to the nearest (remember that this gets shifted out, so it only has an effect if it causes a carry to the next most significant bit position after bit 7), and the >> 8
corrects the position of the point (because multiplying two fixed-point values with 8 fractional bits using integer arithmetic yields a fixed-point value with 16 fractional bits).
The only question then is what that 'x += x >> 8' is for, and that I'm afraid I do now know. In effect it multiplies the result by (1 + 1/256).