user3552515
user3552515

Reputation: 41

Invert specific bits using bitwise NOT (no XOR)

How can I use Bitwise Not to invert specific bits for x number? I know we can do this use XOR and mask but question requires use NOT.

I need to invert a group of bits starting at a given position. The variable inside the function includes original value, position wants to start and width = number of bits I want to invert.

I use the shift bit to start from a given position but how can I ensure only x number of bits are inverted using NOT Bitwise function?

Upvotes: 3

Views: 12736

Answers (3)

Alok
Alok

Reputation: 101

This function will invert 'width' number of bits of number 'num' from position 'pos'

int invert(int num, int pos, int width)
{

  int mask = (~((~0) << width)) << pos;
  num = (~(num & mask)) & mask);

}

Upvotes: 0

chux
chux

Reputation: 153338

Definition of xor: a ^ b <--> (a & ~b) | (~a & b)

unsigned x = 0x0F;
unsigned mask = 0x44;  // Selected bits to invert

unsigned selected_x_bits_inverted = (x & ~mask) | (~x & mask);
printf("%02X\n", selected_x_bits_inverted);
// 4B

Upvotes: 6

Paul92
Paul92

Reputation: 9062

An approach would be:

First, extract them into y:

y = x & mask

Then, invert y and get only the bits you need:

y = ~y & mask

Clear the bits extracted from x:

x = x & (~mask)

OR those 2 numbers to get the result:

x = x | y

Note that every bit that has to be inverted is 1 in mask. Even if I used other bitwise operators, the actual bit flipping is done by a bitwise not. Also, I don't think it is possible to achieve this result without using some other binary operators.

Upvotes: 2

Related Questions