将第i位设置为零? [英] Set the i-th bit to zero?

查看:46
本文介绍了将第i位设置为零?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

无论第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 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.

这篇关于将第i位设置为零?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆