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
ORtarget bits with1sORunchanged bits with0s
Masking bits to 0
ANDtarget bits with0sANDunchanged bits with1s
Querying the status of a bit
ANDtarget bits with1sANDunwanted bits with0s
Toggling bit values
XORtarget bits with1sXORunchanged bits with0s