Common use cases
Check odd/even number
boolean odd(int n) {
return n & 0b1;
}
Half the number
int half(int n) {
return n >> 1;
}
Double the number
int double(int n) {
return n << 1;
}
Masking (opens in a new tab)
- to 1: Y OR 1 = 1, Y OR 0 = Y
- to 0: Y AND 0 = 0, Y AND 1 = Y
Masking bits to 1
OR
target bits with1
sOR
unchanged bits with0
s
Masking bits to 0
AND
target bits with0
sAND
unchanged bits with1
s
Querying the status of a bit
AND
target bits with1
sAND
unwanted bits with0
s
Toggling bit values
XOR
target bits with1
sXOR
unchanged bits with0
s