Optimize Boolean Mask Assignment
<p>This question is similar in nature to: <a href="https://stackoverflow.com/questions/13907111/is-condition-a-correct-way-to-obtain-a-full-bitvector-from-a-boolean-mask-b">Is -!(condition) a correct way to obtain a full-bitvector from a boolean (mask-boolean)?</a></p>

<p>As part of a HW solution, I would like to implement a conditional check and subsequent assignment of all "1" or "0" bits to a 32bit int.</p>

<p><strong>My code is : <code>value &amp; ~(!(x &amp; y) - 1)</code>. If there is some overlap between x's and y's bits, value is set to 0, otherwise value is left alone.</strong></p>

<p><strong>My question is how to optimize this statement to reduce the number of operators involved.</strong> Is this possible using only unary and binary integer operations <code>! ~ &amp; ^ | + - * / % &lt;&lt; &gt;&gt;</code> ?</p>

<p>Here is my code for some reference, it repeats the low-order n bits of x to word length:</p>

<pre><code>int bitRepeat(int x, int n) {
/* Mask desired bits, shift and OR by larger intervals each time, return repeated pattern */    

/* Check for n = 32, set a to all 1's if n != 32 */ 
int nMax = ~(!(n &amp; 31)-1);  

/* Mask low-order n bits */
int maskBits = ~(~0 &lt;&lt; n) &amp; x;  

/* Initialize shift factors */  
int n2 = n * 2; 
int n4 = n * 4; 
int n8 = n * 8; 
int n16 = n * 16;

/* Shift and OR masked bits by intervals n * x {x: 1,2,4,8,16}, check for overflow at each step */  
int overFlowMask = ~0 &lt;&lt; 5;
maskBits = maskBits | maskBits &lt;&lt; n;
maskBits = maskBits | ((maskBits &lt;&lt; (n2)) &amp; ~(!((n2) &amp; overFlowMask) - 1));
maskBits = maskBits | ((maskBits &lt;&lt; (n4)) &amp; ~(!((n4) &amp; overFlowMask) - 1));
maskBits = maskBits | ((maskBits &lt;&lt; (n8)) &amp; ~(!((n8) &amp; overFlowMask) - 1));
maskBits = maskBits | ((maskBits &lt;&lt; (n16)) &amp; ~(!((n16) &amp; overFlowMask) - 1));

return (maskBits &amp; ~nMax) | (x &amp; nMax);
}
</code></pre>

<p>Would implementing <code>unsigned</code> data in some capacity help ?</p>