Is the following solution to the question correct?
My solution is:
#include <stdio.h>
unsigned invert(unsigned x, int p, int n)
{
return (x >> (p + 1 - n)) ^ ~(~0 << n);
}
int main()
{
printf("%d\n", invert(6, 4, 3));
return 0;
}
which prints the output 6
, the binary equivalent of 0110
.
No, it's not correct.
x >> (p+1-n)
will shift all the bits of the original number, so that the most significant ones can't remain unchanged.I'd use something like the following