Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: Bitwise NOT on certain bit

My question is rather simple, yet I cannot find an easy solution: I have an integer greater or eqal 16, so at least 1000 in binary. I wish to flip the third bit using the bitwise NOT operator. In this case, it would be 1100.

Is there any operator which could do this? The ~-operator flips all bits as far as I know, not just one certain.

like image 777
MechMK1 Avatar asked Nov 30 '22 07:11

MechMK1


2 Answers

XOR with the bits that you want to flip.

int c = 0x10; // 10000b
int m = 0x08; // 01000b
c ^= m;       // 11000b
like image 196
Sergey Kalinichenko Avatar answered Dec 15 '22 12:12

Sergey Kalinichenko


Do

bit_fld ^= (1 << n)

where bit_fld is the bit field, and n=3 for third bit.

like image 42
Lie Ryan Avatar answered Dec 15 '22 14:12

Lie Ryan