设置int中的特定位 [英] Set a specific bit in an int
问题描述
我需要通过为每个可能的数据库值设置int值中的特定位来屏蔽从数据库读取的某些字符串值.例如,如果数据库返回字符串"value1",则位置0的位将需要设置为1,但是如果数据库返回"value2",则位置1的位将需要设置为1./p>
如何确保将int的每个位最初设置为0,然后仅打开指定的位?
如果您有int值" intValue ",并且想在位置" bitPosition"上设置特定位, em>",执行以下操作:
intValue = intValue | (1 << bitPosition);
或更短:
intValue |= 1 << bitPosition;
如果您想重置一点(即将其设置为零),则可以执行以下操作:
intValue &= ~(1 << bitPosition);
(运算符~
将值中的每个位取反,因此~(1 << bitPosition)
将产生一个 int ,其中除给定位的位外,每个位均为 1 bitPosition .)
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?
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.)
这篇关于设置int中的特定位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!