https://www.topcoder.com/community/data-science/data-science-tutorials/a-bit-of-fun-fun-with-bits/
The basics
At the heart of bit manipulation are the bit-wise operators
- & (and)
- | (or)
- ~ (not)
- ^ (xor)
Operations
- set union
- A | B
- set intersection
- A & B
- set subtraction
- A & ~B
- set negation
- ALL_BITS ^ A
- set bit, create a 0001000
- A = A | 1 << bit
- clear bit, create a mask like 1110111
- A = A & ~(1 << bit)
- test bit / get bit, create a mask like 000100
- (A & 1 << bit) != 0
- get lowest bit 1 of A
- A & ~(A - 1)
Find the opposite number
in signed 32-bit integers
int num = 45;
int newNum = ~num + 1;
System.out.println(newNum); //=> -45
int back = ~newNum + 1;
System.out.println(back);//=> 45