Boolean algebra
In Boolean algebra, variables have only two values: true and false, usually denoted 1 and 0 respectively.
Four logical operations are widely used in programming:
- and or conjunction
- or or disjunction
- not or negation
- xor or exclusive or, this operation is a combination of three others
arg 1 | arg 2 | AND | XOR | OR | NOT |
---|---|---|---|---|---|
E1 | E2 | E1 & E2 | E1 ^ E2 | E1 | E2 | !E1 |
0 | 0 | 0 | 0 | 0 | 1 |
1 | 0 | 0 | 1 | 1 | 0 |
0 | 1 | 0 | 1 | 1 | 1 |
1 | 1 | 1 | 0 | 1 | 0 |
bitwise operation
In programming sometimes the logic operations apply to the bits of number.
The bitwise NOT is a unary operation that performs logical negation on each bit. Bits that are 0 become 1, and those that are 1 become 0. It is also knows as inversion.
The bit shifts are operations where bits are moved to the left or right. In programming we have fixed number of bits, for example 32 or 64 bits. So some bits will be "shifted out" at one end, while the same number of bits are "shifted in" from the other end. When you are shifting to the left, the new bits are always zero. When you are shifting to the right, the new bits are zero for unsigned numbers and equal to the signed bit for signed numbers.
// example of using bitwise operations
private int f;
// clear all bits
void clear(){
f=0;
}
// set bit i
void set(int i, boolean val) {
int k=1<<i; // shift 0 bit by i
// f=(val)?(f|k):(f&(~k)) or
if(val)
f=f|k;
else
f=f&(~k);
}
// get value of bit i
//Java
boolean isBit(int i) {
return (f&(1<<i)) >0;
}
// C++
bool get(int i) {
return f&(1<<i);
}