+ 1
How to set or clear a bit in a variable without effecting other bits? and also don't use if-else
6 Antworten
+ 2
"clear a bit" means setting one bit to 0?
+ 1
yes
+ 1
I am thinking of bool pointers .... i never tried. but tell me will that work?
+ 1
imagine an integer number i.
to put 0 in bit number n:
i &= ~(1 << n);
to put 1 in bit number n:
i |= (1 << n);
to change the bit number n (1 to 0 and 0 to 1):
i ^= (1 << n);
you could combine the right hand side to make operations in more than 1 bit at a time:
i &= ~(1 << n1) & ~(1 << n2);
This puts 0 in bits n1 and n2.
Edit:
Ramesh ir right.
+ 1
small correction:
clear a bit: i & = ~(1<< n) ;
0
no