Summary:
I'm looking for the fastest way to calculate
(int) x / (int) y
without getting an exception for y==0
. Instead I just want an arbitrary result.
Background:
When coding image processing algorithms I often need to divide by an (accumulated) alpha value. The most simple variant is plain C code with integer arithmetic. My problem is that I typically get a division by zero error for result pixels with alpha==0
. However this are exactly the pixels where the result doesn't matter at all: I don't care about color values of pixels with alpha==0
.
Details:
I'm looking for something like:
result = (y==0)? 0 : x/y;
or
result = x / MAX( y, 1 );
x and y are positive integers. The code is executed a huge number of times in a nested loop, so I'm looking for a way to get rid of the conditional branching.
When y does not exceed the byte range, I'm happy with the solution
unsigned char kill_zero_table[256] = { 1, 1, 2, 3, 4, 5, 6, 7, [...] 255 };
[...]
result = x / kill_zero_table[y];
But this obviously does not work well for bigger ranges.
I guess the final question is: Whats the fastest bit twiddling hack changing 0 to any other integer value, while leaving all other values unchanged?
Clarifications
I'm not 100% sure that branching is too expensive. However, different compilers are used, so I prefer benchmarking with little optimizations (which is indeed questionable).
For sure, compilers are great when it comes to bit twiddling, but I can't express the "don't care" result in C, so the compiler will never be able to use the full range of optimizations.
Code should be fully C compatible, main platforms are Linux 64 Bit with gcc & clang and MacOS.