invert specific bits using bitwise NOT

user3552515 picture user3552515 · Apr 19, 2014 · Viewed 8.7k times · Source

does anyone have experience to 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 bis 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?

Answer

chux - Reinstate Monica picture chux - Reinstate Monica · Apr 20, 2014

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