-1

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?

Tommy Saechao
  • 1,099
  • 4
  • 17
  • 28
  • Possible duplicate of [Bit invert function in K&R exercise 2-7](http://stackoverflow.com/questions/15747123/bit-invert-function-in-kr-exercise-2-7) – ashiquzzaman33 Dec 05 '15 at 09:37

1 Answers1

1

In my opinion it is much simpler to write the function the following way. I suppose that the position starts from 0.

int invert( int x, int p, int n )
{
    unsigned int mask = ~( ~0 << n ) << p;

    return x ^ mask;;
}    

As for your function then at least these statements

//gets rid of bits before position p
inverted_x = inverted_x << (p - 1);
inverted_x = inverted_x >> (p - 1);

are already wrong. They do not do what you think.

It would be correctly to write

//gets rid of bits before position p
inverted_x = inverted_x >> p;
inverted_x = inverted_x << p;

Nevertheless to perform this operation does not make sense because low bits of the original number are lost

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335