The following truth table shows the logical operations AND, OR (inclusive or) and EOR (exclusive or) on two bits A and B:
-
-
+----------------------------------+
-
¦ A ¦ B ¦ AND ¦ OR ¦ EOR ¦
-
+-----+-----+-------+------+-------¦
-
¦ 0 ¦ 0 ¦ 0 ¦ 0 ¦ 0 ¦
-
¦ 0 ¦ 1 ¦ 0 ¦ 1 ¦ 1 ¦
-
¦ 1 ¦ 0 ¦ 0 ¦ 1 ¦ 1 ¦
-
¦ 1 ¦ 1 ¦ 1 ¦ 1 ¦ 0 ¦
-
+----------------------------------+
-
& bitwise and operator& bitwise and operatorThe C bitwise logical operators & (and), | (or) and ^ (exclusive or) have two integral operands and perform the specified operation upon the corresponding bits in each operand.
-
k = i & j; /* logical AND, i & j, assign result to k */
-
k = i | j; /* logical inclusive OR, i | j, assign result to k */
-
k = i ^ j; /* logical exclusive OR, i ^ j, assign result to k */
-
For example, assuming that i and j are byte sized variables having the values 00001010 and 01001100 respectively, the following table shows the result of &, | and ^ operations.
-
+------------------------------------------------------------+
-
¦ operation ¦ operator ¦ example operation ¦ result ¦
-
+--------------+------------+---------------------+----------¦
-
¦ AND ¦ i & j ¦ 00001010 & 01001100 ¦ 00001000 ¦
-
¦ ¦ ¦ ¦ ¦
-
¦ inclusive OR ¦ i | j ¦ 00001010 | 01001100 ¦ 01001110 ¦
-
¦ ¦ ¦ ¦ ¦
-
¦ exclusive OR ¦ i ^ j ¦ 00001010 ^ 01001100 ¦ 01000110 ¦
-
+------------------------------------------------------------+
-
e.g. a program to set bits
-
#include <stdio.h>
-
int main()
-
{
-
int bit, z=0;;
-
while(1)
-
{
-
printf("enter bit to set ? ");
-
scanf("%d", &bit);
-
z = z | (1 << bit);
-
printf("z=%x \n", z);
-
}
-
return 0;
-
}
-
the loop
1. read the bit number, e.g. 5
2. shift 1 left by that number of bits, e.g. 0x20
3. OR it into z
a run gave:
enter bit to set ? 5
z=20
enter bit to set ? 0
z=21
Another bitwise operator is unary ~ (not or one's complement) which inverts the value of every bit in the operand, i.e. 0 becomes 1 and 1 becomes 0, e.g. for 00001010 the one's complement would be 11110101
i = ~i