将第i位设置为零? [英] Set the i-th bit to zero?
问题描述
无论第i位是什么,我都希望将第i位设置为零.
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...
将其设置为1,我们可以使用遮罩pt | (1 << i)
,但我不确定如何为设置0创建遮罩.
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.
推荐答案
您只需要将逻辑OR
替换为逻辑AND
操作.您可以使用&
运算符:
You just have to replace the logical OR
with a logical AND
operation. You would use the &
operator for that:
pt = pt & ~(1 << i);
您必须反转您的掩码,因为用1
进行逻辑AND
的操作将保留该位,而0
将其清除的位...因此您需要指定一个0
在您要清除的位置.具体来说,执行1 << i
将为您提供一个掩码,该掩码为000...010..000
,其中1
处于所需的位位置,然后将其反转将得到111...101...111
.对此进行逻辑AND
处理将清除您想要的位.
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. 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 AND
ing with this will clear the bit that you want.
这篇关于将第i位设置为零?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!