In Java, is it possible to clear a bit using bitwise operations?
Java enables you to manipulate integers on a bit level, that means operating on specific bits, which represent an integer number. In some cases, it can be really handy.
BitClear(value1, bitpos) The parameters specify the numeric value and the bit position on which the operation is performed. The specified bit is set to a zero (0) in the value provided. If the bit was not on, the value is unchanged. Specifying a negative or zero bit position does not result in any change to the value.
yes, using
bits & ~(1 << n)
where bits is an int/long and n is the n-th bit to be cleared.
(this is a useful blog post: low level bit hacks you absolutely must know)
An alternative to dfa's answer would be to use a BitSet datastructure. It supports operations such as AND, OR and 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)
.
If you have to use integers, then set value using bits |= (1 << N)
and as
dfa mentioned, clear using: bits &= ~(1 << N)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With