title: copy n bits at given position from x to y in C
body: <p>I am learning C and I am still a very beginner.</p>
  
  <p>My problem is the following. I have one unisgned int x and one unsigned int y. I would like to copy n bits from position p from x to the same position on y. I found some similar problems but not in C and most of the time the problem is slightly different if one takes the most right or left bits. I would also like to find a solution not depending on integer representation on the machine.</p>
  
  <p>Here is what I did </p>
  
  <pre><code>unsigned fix_bits(unsigned x, unsigned y, int n, int p)
  {
      unsigned u1,u2,u3,u4,x1,y1,yf;
      u1 = ~0; /*vector of 1*/
      u2 = (u1&gt;&gt;n); /*0 from 0 to n-1 and 1s*/
      u3 = ~(u2);/*1 from 0 to n-1 and 0s*/
      u4 = u3&gt;&gt;p;/*0 from 0 to p-1, n 1 from p to p+n+1 and 0s*/
      x1 = (x &amp; u4);/*only keep n bits of x from position p*/
      y1 = (y | u4);/*set y bit  from p to (p+n+1) to 1, rest remains unchanged (0 | bit = bit)*/
      yf = (x1 | y1);
      return yf;
  }
  </code></pre>
  
  <p>But it does not work: </p>
  
  <p>The result of placing 2 bits at position 3 of 28 to 32 is 402653216</p>
  
  <p>Does someone knows what am I doing wrong ?</p>
  
  <p>Thank you very much</p>