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
2009-07-02 09:13:40
Adrian Panasiuk
2009-07-02 09:15:55
The blog post link was especially useful, thank you.
byte
2009-07-02 09:22:26
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
2009-07-02 09:46:35