在Java中,是否可以使用逐位操作来清除位?
发布于 2009-07-02 09:13:41
是的,使用
bits & ~(1 << n) 其中,位是整型/长整型,n是要清除的第n位。
(这是一篇有用的博客文章:)
发布于 2020-03-01 08:55:28
对于dfa的答案,另一种选择是使用BitSet datastructure。支持AND、OR、XOR等运算。
var bitset = new BitSet(K); // Initialize a bitset with K digits.
var nthBit = bitset.get(n); // Get Nth bit (true/false).
bitset.clear(n); // Clears N'th bit to false.
bitset.set(n); // Sets N'th bit to true.
bitset.flip(n); // Toggles N'th bit.在您的示例中,您将查找bitset.clear(n)。
如果必须使用整数,则使用bits |= (1 << N)设置值,并如前面提到的那样,清除使用:bits &= ~(1 << N)。
https://stackoverflow.com/questions/1073318
复制相似问题