Note that there are some explanatory texts on larger screens.

plurals
  1. POWhat is the fastest integer division supporting division by zero no matter what the result is?
    primarykey
    data
    text
    <p><strong>Summary:</strong></p> <p>I'm looking for the fastest way to calculate</p> <pre><code>(int) x / (int) y </code></pre> <p>without getting an exception for <code>y==0</code>. Instead I just want an arbitrary result.</p> <hr> <p><strong>Background:</strong></p> <p>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 <code>alpha==0</code>. However this are exactly the pixels where the result doesn't matter at all: I don't care about color values of pixels with <code>alpha==0</code>.</p> <hr> <p><strong>Details:</strong></p> <p>I'm looking for something like:</p> <pre><code>result = (y==0)? 0 : x/y; </code></pre> <p>or</p> <pre><code>result = x / MAX( y, 1 ); </code></pre> <p>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.</p> <p>When y does not exceed the byte range, I'm happy with the solution</p> <pre><code>unsigned char kill_zero_table[256] = { 1, 1, 2, 3, 4, 5, 6, 7, [...] 255 }; [...] result = x / kill_zero_table[y]; </code></pre> <p>But this obviously does not work well for bigger ranges.</p> <p>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?</p> <hr> <p><strong>Clarifications</strong></p> <p>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).</p> <p>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.</p> <p>Code should be fully C compatible, main platforms are Linux 64 Bit with gcc &amp; clang and MacOS.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload