21

I'm new at programming. Recently i came across a problem in which i have to make a particular bit 0 of a number.

For example :

I have a number p

p      = 73
binary = 1001001

Now i want to make 4th bit to 0, that is 1000001(2) = 65(10)

I did this in following way :

int p = 73;
int pos = 1<<3; // 4th bit
int max_bit = (1<<31) - 1; // making all bit to 1
int mask = pos ^ max_bit; // making 4th bit to 0 except others
p = p & mask; // changing 4th bit of p to 0
cout<<p<<endl;

Is there a better way to do this ?

Elliot
  • 213
  • 2
  • 5

1 Answers1

19

Just use :

p = p & ~(1u<<3);

What happens here ?

 1. (1u<<3)       0...01000
 2. ~(1u<<3)      1...10111 // Invert the bits
 3. p & ~(1u<<3)  *****0*** // Here * means the bit representation of p

That's how the bit changes to 0.
Hope it helps :)

Ali Akber
  • 3,670
  • 3
  • 26
  • 40