Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set the i-th bit to zero? [duplicate]

I would like to set the i-th bit to zero no matter what the i-th bit is.

  unsigned char pt = 0b01100001;
  pt[0] = 0; // its not how we do this... 

Setting it to one, we can use a mask pt | (1 << i) but i'm not sure how to create a mask for setting 0, if thats possible.

like image 327
GivenPie Avatar asked Sep 23 '14 20:09

GivenPie


People also ask

How do you set a ith bit to 0?

You just have to replace the logical OR with a logical AND operation. You would use the & operator for that: pt = pt & ~(1 << i); You have to invert your mask because logical AND ing with a 1 will maintain the bit while 0 will clear it... so you'd need to specify a 0 in the location that you want to clear.

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.

What is the bitwise operator used to set a particular bit to zero 0?

3. Which of the following bitwise operations will you use to set a particular bit to 0? Explanation: 1 AND 0 = 0, 0 AND 0 = 0, any bit AND with 0 gives 0.

How do you flip a bit in C++?

bitset::flip() is a built-in STL in C++ which flips the bits. If no parameter is passed in the function, then it flips all the bit values converting zeros to ones and ones to zeros. If a parameter position is passed, it flips the bit at the position only.


2 Answers

You just have to replace the logical OR with a logical AND operation. You would use the & operator for that:

pt = pt & ~(1 << i);

You have to invert your mask because logical ANDing with a 1 will maintain the bit while 0 will clear it... so you'd need to specify a 0 in the location that you want to clear. Specifically, doing 1 << i will give you a mask that is 000...010..000 where the 1 is in the bit position that you want, and inverting this will give 111...101...111. Logical ANDing with this will clear the bit that you want.

like image 81
rayryeng Avatar answered Oct 05 '22 03:10

rayryeng


You could stick with this:

// Set bit at position `bitpos` in `pt` to `bitval`
unsigned char bitpos = 1;
unsigned char pt = 0b01100001;
bool bitval = 1;

// Clear the bit
pt &= ~(1u << bitpos);
// Set the bit
pt |= (bitval << bitpos);
like image 43
marco-a Avatar answered Oct 05 '22 04:10

marco-a