27.1k views
2 votes
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.

User ITWorker
by
8.4k points

1 Answer

5 votes

Final answer:

The invert function flips n bits of an integer x starting from position p, which is achieved by creating a mask with n 1's bit-shifted over p positions and then applying an XOR operation with x to invert those bits.

Step-by-step explanation:

The invert function takes an integer x, a position p, and several bits n, and flips the n bits starting at position p. To achieve this, you can use a mask with n 1's shifted p positions over. This mask is created by shifting 1 left by n positions, subtracting 1 to get a sequence of 1's, and then shifting again by p to get the mask in the correct position. The invert function is applied to x by using an XOR operation which inverts each bit where the mask is 1 and leaves other bits unchanged.

Example Function in C:

unsigned invert(unsigned x, unsigned p, unsigned n) {
unsigned mask = ((1 << n) - 1) << p;
return x ^ mask;
}

User Peroyomas
by
7.4k points