Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java, is it possible to clear a bit?

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

like image 712
dreadwail Avatar asked Jul 02 '09 09:07

dreadwail


People also ask

Can Java manipulate bit?

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.

What is bit clear operation?

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.


2 Answers

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)

like image 114
dfa Avatar answered Nov 11 '22 17:11

dfa


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

like image 36
Adithya Upadhya Avatar answered Nov 11 '22 18:11

Adithya Upadhya