views:

308

answers:

1

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

+6  A: 

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)

dfa
Adrian Panasiuk
The blog post link was especially useful, thank you.
byte
Care needs to be taken if n is > 31, the “1” needs to be “1L” in that case otherwise the shift operation will only use the five lowest bits of n. (See JLS, § 15.19.)
Bombe