C: Bitwise NOT on a specific bit

My question is pretty simple, but I cannot find an easy solution: I have an integer greater than or equal to 16, so at least 1000 in binary format. I want to flip the third bit using the bitwise NOT operator. In this case, it will be 1100 .

Is there any operator that could do this? As far as I know, the ~ -operator flips all bits, not just some.

+4
source share
5 answers

XOR with the bits you want to flip.

 int c = 0x10; // 10000b int m = 0x08; // 01000b c ^= m; // 11000b 
+10
source

Do

 bit_fld ^= (1 << n) 

where bit fld is a bit, and n = 3 for the third bit.

+4
source

Now what you call "flip" is actually called XOR. XOR in C (++) works as follows:

 int sixteen = 16; // 10000 int twentyfour = sixteen ^ 0x8; // flip the 4th bit. result: 24 int sixteen_again = twentyfour ^ 0x8; // again, flip the 4th bit. result: 16 

On a side note: 16 in binary format - 10000, not 1000.

+3
source

check this site: http://www.daniweb.com/software-development/c/threads/41493 it has the same problem as yours and a couple of solutions!

 void flipbit(unsigned* a, unsigned b) { *a ^= (1 << b); } 
+2
source
 #include <stdio.h> int main(void) { int x = 0xFFFFFFFF; int n = 0; int y, i; for (i=0 ; i < (int)sizeof(int)*8 ; i++) { y = x ^ ~(1<<i); printf("x=%x\ti=%d\ty=%x\n", x, i, y); } x = 0x0; for (i=0 ; i < (int)sizeof(int)*8 ; i++) { y = x ^ ~(1<<i); printf("x=%x\ti=%d\ty=%x\n", x, i, y); } return 0; } /* Output: x=ffffffff i=0 y=1 x=ffffffff i=1 y=2 x=ffffffff i=2 y=4 x=ffffffff i=3 y=8 x=ffffffff i=4 y=10 x=ffffffff i=5 y=20 x=ffffffff i=6 y=40 x=ffffffff i=7 y=80 x=ffffffff i=8 y=100 x=ffffffff i=9 y=200 x=ffffffff i=10 y=400 x=ffffffff i=11 y=800 x=ffffffff i=12 y=1000 x=ffffffff i=13 y=2000 x=ffffffff i=14 y=4000 x=ffffffff i=15 y=8000 x=ffffffff i=16 y=10000 x=ffffffff i=17 y=20000 x=ffffffff i=18 y=40000 x=ffffffff i=19 y=80000 x=ffffffff i=20 y=100000 x=ffffffff i=21 y=200000 x=ffffffff i=22 y=400000 x=ffffffff i=23 y=800000 x=ffffffff i=24 y=1000000 x=ffffffff i=25 y=2000000 x=ffffffff i=26 y=4000000 x=ffffffff i=27 y=8000000 x=ffffffff i=28 y=10000000 x=ffffffff i=29 y=20000000 x=ffffffff i=30 y=40000000 x=ffffffff i=31 y=80000000 x=0 i=0 y=fffffffe x=0 i=1 y=fffffffd x=0 i=2 y=fffffffb x=0 i=3 y=fffffff7 x=0 i=4 y=ffffffef x=0 i=5 y=ffffffdf x=0 i=6 y=ffffffbf x=0 i=7 y=ffffff7f x=0 i=8 y=fffffeff x=0 i=9 y=fffffdff x=0 i=10 y=fffffbff x=0 i=11 y=fffff7ff x=0 i=12 y=ffffefff x=0 i=13 y=ffffdfff x=0 i=14 y=ffffbfff x=0 i=15 y=ffff7fff x=0 i=16 y=fffeffff x=0 i=17 y=fffdffff x=0 i=18 y=fffbffff x=0 i=19 y=fff7ffff x=0 i=20 y=ffefffff x=0 i=21 y=ffdfffff x=0 i=22 y=ffbfffff x=0 i=23 y=ff7fffff x=0 i=24 y=feffffff x=0 i=25 y=fdffffff x=0 i=26 y=fbffffff x=0 i=27 y=f7ffffff x=0 i=28 y=efffffff x=0 i=29 y=dfffffff x=0 i=30 y=bfffffff x=0 i=31 y=7fffffff */ 

I refer to this link for bit operations in c .

+1
source

Source: https://habr.com/ru/post/1388016/


All Articles