Creating a specific "0" bit in C ++

I am new to programming. I recently ran into a problem in which I have to make a specific bit 0 of a number.

For instance:

I have a number p

p = 73 binary = 1001001 

Now I want to make the 4th bit equal to 0, i.e. 1000001 (2) = 65 (10)

I did it as follows:

 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?

+6
source share
1 answer

Just use:

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

What's going on 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 

The way the bit changes to 0.
Hope this helps :)

+14
source

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


All Articles