Set a specific bit in an int

旧城冷巷雨未停 提交于 2019-12-18 04:39:24

问题


I need to mask certain string values read from a database by setting a specific bit in an int value for each possible database value. For example, if the database returns the string "value1" then the bit in position 0 will need to be set to 1, but if the database returns "value2" then the bit in position 1 will need to be set to 1 instead.

How can I ensure each bit of an int is set to 0 originally and then turn on just the specified bit?


回答1:


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.)




回答2:


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.



来源:https://stackoverflow.com/questions/24250582/set-a-specific-bit-in-an-int

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