Programming machines has always been a difficult task; newer techniques try to solve this by automating the tougher tasks, the low-level handling of the machines. However, some gates have been left open to the older methods, so whenever you wish to use them you are able to do so. At least this applies to C/C++. In this article you'll see how to use bitwise operators in C/C++, and learn why you may want to use them.
Bitwise Operators - Bitwise and, or, and exclusive or (Page 3 of 5 )
This is the "and" (&) operator. In order to use it, you need two integers. The operator takes each of them and compares the numbers, bit by bit. The first bit from the first integer is compared with the first bit of the second integer, and if both are 1s (true) then in the result the first bit will also be 1. The and operator will then do this for all of the remaining bits.
The bitwise "or" (|), in the same fashion passes through the integer, but if one of the bits is 1 (true), then the result will also be 1 (true). So the only way that a bit will be 0 (false) is if both of them are 0s.
On the other hand, the bitwise "exclusive or" (^) applies the rule that the result is 1 (true) whenever the bits to which the operator was applied on the n-th place are of a different type. Thus, 1 will be generated only for "1-0" or "0-1" combinations.
For example:
unsigned char a = 1, b = 3,c=0;
// a = 00000001
// b = 00000011
c = a & b ; // -> 00000001
c = a | b ; // -> 00000011
c = a ^ b ; // -> 00000010
Bitwise ~ (Negation)
Now we also have the bitwise negation. Please don't mix it up with the negation, because for that task we already have another operator, the "!". The bitwise negation negates each bit of the integer. This means it changes the 1s to 0s and vice-versa. Call it a bit flipper if you want, and also notice that this will be the complement of the byte. For this we only need a single integer to use it in the following mode: