Reputation: 21
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
.
Upvotes: 0
Views: 727
Reputation: 12749
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
unsigned invert(unsigned x, int p, int n)
{
int const n_bits = sizeof(x) * CHAR_BIT;
assert(p >= 0 && p < n_bits);
assert(n >= 0 && n + p <= n_bits);
if ( n == 0 )
return x;
unsigned const mask = (~0u >> (n_bits - n)) << p;
return x ^ mask;
}
Upvotes: 3