+ 1

How to set or clear a bit in a variable without effecting other bits? and also don't use if-else

26th Jun 2016, 8:17 AM
Ramesh Marisa
6 Réponses
+ 2
"clear a bit" means setting one bit to 0?
26th Jun 2016, 8:41 AM
Mukul Kumar
Mukul Kumar - avatar
+ 1
yes
26th Jun 2016, 9:46 AM
Ramesh Marisa
+ 1
I am thinking of bool pointers .... i never tried. but tell me will that work?
26th Jun 2016, 2:25 PM
Mukul Kumar
Mukul Kumar - avatar
+ 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.
26th Jun 2016, 2:31 PM
Garme Kain
Garme Kain - avatar
+ 1
small correction: clear a bit: i & = ~(1<< n) ;
26th Jun 2016, 2:47 PM
Ramesh Marisa
0
no
1st Jul 2016, 2:16 PM
antonette colebra
antonette colebra - avatar