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

陌路散爱 提交于 2019-11-29 11:05:46

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.

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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!