java 在Java中,是否可以清除一点?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1073318/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 15:04:15  来源:igfitidea点击:

In Java, is it possible to clear a bit?

javabit-manipulation

提问by dreadwail

In Java, is it possible to clear a bit using bitwise operations?

在 Java 中,是否可以使用按位运算清除一点?

回答by dfa

yes, using

是的,使用

bits & ~(1 << n) 

where bitsis an int/long and nis the n-th bit to be cleared.

其中bits是 int/long,n是要清除的第 n 位。

(this is a useful blog post: low level bit hacks you absolutely must know)

(这是一篇有用的博客文章:你绝对必须知道的低级位黑客

回答by Adithya Upadhya

An alternative to dfa's answer would be to use a BitSet datastructure. It supports operations such as AND, OR and XOR.

dfa 答案的替代方法是使用BitSet 数据结构。它支持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.

In your case, you'll be looking for bitset.clear(n).

在您的情况下,您将寻找bitset.clear(n).

If you have to use integers, then set value using bits |= (1 << N)and as dfa mentioned, clear using: bits &= ~(1 << N).

如果您必须使用整数,则使用bits |= (1 << N)和如 dfa 所述设置值,清除使用:bits &= ~(1 << N)