Exercise 2-7. Write a function invert(x,p,n) that returns x with the n bits that begin at position p inverted (i.e., 1 changed into 0 and vice versa), leaving the others unchanged.
#include <cstdio>
int invert(unsigned int x, int p, int n)
{
int inverted_x = ~x;
//gets rid of bits before position p
inverted_x = inverted_x << (p - 1);
inverted_x = inverted_x >> (p - 1);
//gets rids of bits after position p+n
inverted_x = inverted_x >> ((sizeof(x) * 8) - (p + n));
inverted_x = inverted_x << ((sizeof(x) * 8) - (p + n));
return inverted_x;
}
int main()
{
int a = 123;
printf("%d \n", invert(a, 2, 3));
}
What am I doing wrong?