Set a specific bit in an int

大城市里の小女人 提交于 2019-12-04 01:25:44

If you have an int value "intValue" and you want to set a specific bit at position "bitPosition", do something like:

intValue = intValue | (1 << bitPosition);

or shorter:

intValue |= 1 << bitPosition;


If you want to reset a bit (i.e, set it to zero), you can do this:

intValue &= ~(1 << bitPosition);

(The operator ~ reverses each bit in a value, thus ~(1 << bitPosition) will result in an int where every bit is 1 except the bit at the given bitPosition.)

To set everything to 0, AND the value with 0x00000000:

int startValue = initialValue & 0x00000000;
//Or much easier :)
int startValue = 0;

To then set the bit, you have to determine what number has just that bit set and OR it. For example, to set the last bit:

int finalValue = startValue | 0x00000001;

As @Magus points out, to unset a bit you do the exact opposite:

int finalValue = startValue & 0xFFFFFFFE;
//Or
int finalValue = startValue & ~(0x00000001);

The ~ operatior is bitwise not which flips every bit.

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