C examples for Operator:Bit Operator
Bitwise operation can test, set, or shift the bits in char and int data types.
You cannot use bitwise operations on float, double, long double, void.
Operator | Action |
---|---|
& | AND |
| | OR |
^ | Exclusive OR (XOR) |
~ | One's complement (NOT) |
>> | Shift right |
<< | Shift left |
The bitwise AND, OR, and NOT are governed by the same truth table as their logical equivalents, except that they work bit by bit.
The exclusive OR has the truth table shown here:
p | q | p ^q |
---|---|---|
0 | 0 | 0 |
1 | 0 | 1 |
1 | 1 | 0 |
0 | 1 | 1 |
The outcome of an XOR is true only if exactly one of the operands is true; otherwise, it is false.
The bitwise shift operators can also quickly multiply and divide integers.
A shift right effectively divides a number by 2 and a shift left multiplies it by 2.
The following program illustrates the shift operators:
#include <stdio.h> int main(void) { unsigned int i; int j;/* w ww . j a v a2 s .co m*/ i = 1; /* left shifts */ for (j = 0; j<4; j++) { i = i << 1; /* left shift i by 1, which is same as a multiply by 2 */ printf("Left shift %d: %d\n", j, i); } /* right shifts */ for (j = 0; j<4; j++) { i = i >> 1; /* right shift i by 1, which is same as a division by 2 */ printf("Right shift %d: %d\n", j, i); } return 0; }
The NOT bit operator, ~, reverses the state of each bit in its operand. That is, all 1's are set to 0, and all 0's are set to 1.
unsigned char x; | binary | value of x |
---|---|---|
x = 7; | 00000111 | 7 |
x = x<<l; | 00001110 | 14 |
x = x<<3; | 01110000 | 112 |
x = x<<2; | 11000000 | 192 |
x = x>>l; | 01100000 | 96 |
x = x>>2; | 00011000 | 24 |
Each left shift multiplies by 2.
Notice that information has been lost after x<<2 because a bit was shifted off the end.