title: Attempting to perform a bitwise manipulation in C, unexpected results
body: <p>So I'm currently trying to finish some university homework that deals with bitwise manipulations, and one of the exercises is giving me the worst kind of trouble, the one where you dont know where you went wrong. The exercise is as follows: </p>
  
  <blockquote>
    <p>Implement the function int activate_bits(int a, int left, int right ) that should ’activate’
    all the bits to the left of left and to the right of right on the number a (excluding the bits
    left and right).</p>
  </blockquote>
  
  <p>My code regarding the activate_bits function is the following </p>
  
  <pre><code>#include &lt;stdio.h&gt;
  
  unsigned int activate_bits(unsigned a, int left, int right){
  
  int mask1 = 1;
  int mask2 = 1;
  int mask3 = 0;
  
  int i;
  
  /* assuming an int as only 8 bits for convenience, what I want to do here is 
  shift the least significant bit to the left, then add 1,as many times as 
  necessary(according to the parameter right), so that the number 00000001 
  becomes 00000011 and so forth */
  
  for (i= (right -1); i&lt;right ; i++){
  
      mask1 &lt;&lt; 1;
      mask1 = mask1 +1 ;
  
  }
  
  /* doing the same as above here, checking how many activated bits the second 
  mask should actually have by doing (32 - left ) */  
  
  for (i = (32 - left); i &lt; 0; i--){
  
      mask2 &lt;&lt; 1;
      mask2 = mask2 +1 ;
  
  }
  
  /* now I'm shifting the second mask as many times as needed so it is placed 
  after the bit position indicated by the left parameter */
  
  mask2 &lt;&lt; left;
  
  mask3 = mask1 + mask2;
  
  return a | mask3;
  
  }
  </code></pre>
  
  <p>Can anyone help me as to why this is giving me a wrong result ?
  Thanks in advance</p>