TOPIC 7.1.2
Bitwize Operators


The following operators are bitwise operators:

Operator        Function                Example
&               (Bitwise AND)           x & 8
|               (Bitwise OR)            x | 8
^               (Bitwise XOR)           x ^ 8
~               (Bitwise NOT)           ~x
>>              (Bitwise shift right)   x >> 3
<<              (Bitwise shift left)    x << 3

The compound bitwise operators can be found under topic 5.1.2 Compound Operators.

Bit fields are useful in storing data with the minimum number of bits required in a class or structure. This allows better memory utilization.

Example:

struct bitBirthDate{
   unsigned month : 4;
   unsigned day : 5;
   unsigned year : 11;
}

The preceding structure defanition indicates that member month is stored in 4 bits, member day is stored in 5 bits, and member year is stored in 11 bits. The number of bits is based on the desired rang of values for each strucre member. Member day stores values from 0 (Jan.) to 11(Dec.) -- 4 bits can store the values from 0 to 2^4-1 = 15. Member day can store the values 0 to 31 -- 5 bits can store the values from 0 to 2^5-1 = 31. Member year stores vaues from 0 to 2047. If 0 represents the year 1, this structure can represent birthdays until the year 2048.

An example using bitwize operators:

#include <iostream.h>

main()
{
   unsigned int number1, number2;

   number1 = 15;  //00001111 in binary
   number2 = 1;   //00000001 in binary

   cout << (number1 & number2) << '\n';  //output 1   or 00000001 in binary

   number2 = 240; //11110000 in binary

   cout << (number1 | number2);          //output 255 or 11111111 in binary
}