Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making a particular bit "0" in C++ [duplicate]

Tags:

c++

bit

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 ?

like image 694
Elliot Avatar asked Dec 30 '14 13:12

Elliot


People also ask

How do you make a certain bit zero?

Just use : p = p & ~(1u<<3); What happens here ? That's how the bit changes to 0.

How do you change a nth bit to a zero?

Setting a bit Use the bitwise OR operator ( | ) to set a bit. number |= 1UL << n; That will set the n th bit of number . n should be zero, if you want to set the 1 st bit and so on upto n-1 , if you want to set the n th bit.

How do I turn off a particular bit in a number?

The idea is to use bitwise <<, & and ~ operators. Using expression “~(1 << (k – 1))“, we get a number which has all bits set, except the k'th bit. If we do bitwise & of this expression with n, we get a number which has all bits same as n except the k'th bit which is 0.

How do you clear a bit?

Clearing a bit Use the bitwise AND operator ( & ) to clear a bit. number &= ~(1 << x); That will clear bit x . You must invert the bit string with the bitwise NOT operator ( ~ ), then AND it.


1 Answers

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 :)

like image 92
Ali Akber Avatar answered Oct 12 '22 23:10

Ali Akber