Note that there are some explanatory texts on larger screens.

plurals
  1. POConstrain a 16 bit signed value between 0 and 4095 using Bit Manipulation only (without branching)
    primarykey
    data
    text
    <p>I want to constrain the value of a <code>signed short</code> variable between 0 and 4095, after which I take the most significant 8 bits as my final value for use elsewhere. Right now I'm doing it in a basic manner as below:</p> <pre><code>short color = /* some external source */; /* * I get the color value as a 16 bit signed integer from an * external source I cannot trust. 16 bits are being used here * for higher precision. */ if ( color &lt; 0 ) { color = 0; } else if ( color &gt; 4095 ) { color = 4095; } unsigned char color8bit = 0xFF &amp; (color &gt;&gt; 4); /* * color8bit is my final value which I would actually use * in my application. */ </code></pre> <p>Is there any way this can be done using bit manipulation only, i.e. without using any conditionals? It might help quite a bit in speeding things up as this operation is happening thousands of time in the code.</p> <p>The following won't help as it doesn't take care of edge cases such as negative values and overflows:</p> <pre><code>unsigned char color8bit = 0xFF &amp; (( 0x0FFF &amp; color ) &gt;&gt; 4 ); </code></pre> <p><strong>Edit:</strong> <a href="https://stackoverflow.com/a/12308926/1044750">Adam Rosenfield's answer</a> is the one which takes the correct approach but its incorrectly implemented. <a href="https://stackoverflow.com/a/12309664/1044750">ouah's answer</a> gives correct results but takes a different approach that what I originally intended to find out.</p> <p>This is what I ended up using:</p> <pre><code>const static short min = 0; const static short max = 4095; color = min ^ (( min ^ color ) &amp; -( min &lt; color )); color = max ^ (( color ^ max ) &amp; -( color &lt; max )); unsigned char color8bit = 0xFF &amp; (( 0x0FFF &amp; color ) &gt;&gt; 4 ); </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    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