#include <stdio.h>

/**
 * Exercise 2-7.  Write a function invert(x,p,n) that returns 
 * x with the n bits that begin at position p inverted, leaving 
 * the others unchanged.
 */

void displaybits(unsigned,int);
unsigned getbits(unsigned,int,int);
unsigned invert(unsigned,int,int);

void displaybits(unsigned x, int numbits)
{
   int i;
   for(i=numbits-1; i>=0; i--)
      printf("%d",(x&(1<<i))>0 ? 1 : 0);
   printf("\n");
}

unsigned getbits(unsigned x, int p, int n)
{
   return (x >> (p+1-n)) & ~(~0 << n);
}

unsigned invert(unsigned x, int p, int n)
{
   int changedbits = getbits(x,p,n) ^ (~(~0<<n)); /* Invert n bits of x at position p */
   int xbits_upper = getbits(x,31,31-p);          /* Get upper (unchanged) bits in x  */
   int xbits_lower = getbits(x,p-n,p+1-n);        /* Get lower (unchanged) bits in x  */
   return (xbits_upper << p+1) | (changedbits << (p+1-n)) | xbits_lower;
}

int main(void)
{
   unsigned x = 128482;
   displaybits(x,32);
   /* Invert four bits at position 10 */
   displaybits(invert(x,10,4),32);
   return 0;
}
