Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<pre><code>short color = /* ... */ color = ((((!!(color &gt;&gt; 12)) * 0xFFF)) | (!(color &gt;&gt; 12) * color )) &amp; (!(color &gt;&gt; 15) * 0xFFF); unsigned char color8bit = 0xFF &amp; (color &gt;&gt; 4); </code></pre> <p>It assumes two's complement representation.</p> <p>This has the advantage of not using any equality or relational operators. There are situations you want to avoid branches at all costs: in some security applications you don't want the attackers to perform branch predictions. Without branches (in embedded processors particularly) you can make your function run in constant time for all inputs.</p> <p>Note that: <code>x * 0xFFF</code> can be further reduced to <code>(x &lt;&lt; 12) - x</code>. Also the multiplication in <code>(!(color &gt;&gt; 12) * color )</code> can also be further optimized as the left operand of <code>*</code> here is <code>0</code> or <code>1</code>.</p> <p><strong>EDIT:</strong></p> <p>I add a little explanation: the expression above simply does the same as below without the use of the conditional and relational operators:</p> <pre><code>y = ((y &gt; 4095 ? 4095 : 0) | (y &gt; 4095 ? 0 : y)) &amp; (y &lt; 0 ? 0 : 4095); </code></pre> <p><strong>EDIT2:</strong></p> <p>as @HotLicks correctly noted in his comment, the <code>!</code> is still a conceptual branch. Nevertheless it can also be computed with bitwise operators. For example <code>!!a</code> can be done with the trivial:</p> <pre><code>b = (a &gt;&gt; 15 | a &gt;&gt; 14 | ... | a &gt;&gt; 1 | a) &amp; 1 </code></pre> <p>and <code>!a</code> can be done as <code>b ^ 1</code>. And I'm sure there is a nice hack to do it more effectively. </p>
 

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