Bitwise operations
While you don’t see them every day, bitwise operations are important. Everything at the hardware level is represented in binary (base 2, 1 and 0). Bitwise operations allow programmers to operate directly on the bits used by variables. This is very useful with enums, since you can have one variable be multiple values.
To understand how one enum variable can be multiple values, you need to understand the bitwise AND and OR operations.
An OR operation compares two sets of bits. If either bit is 1, the result is 1, else, result is 0. In the below example, set 1 is the value of enum option 1, and set 2 is the value of enum option 2.
Set 1: 11001000 Set 2: 00110110 Result: 11111110
An AND operation compares two sets of bits. If both bits are 1, the result is 1, else, result is 0. In the below example, set 1 is enum option 1, and set 2 is the result from the OR above.
Set 1: 11001000 Set 2: 11111110 Result: 11001000
Notice what the result is? enum option 1. Using this logic, we can create the following snippet:
enum Status {STOP, START, RUN};
// Bitwise OR of START and RUN
Status s = START | RUN;
// If the result of a bitwise AND of s and START is START
// (if condition is true)
if ((s & START) == START))
cout << "s is Start." << endl;
// If the result of a bitwise AND of s and RUN is RUN
// (if condition is true)
if ((s & RUN) == RUN))
cout << "s is Run." << endl;
Pretty neat right? Well, there's one more use that I learned yesterday.
Suppose you wanted to find out if an integer was a power of 2. One person volunteered a somewhat complex algorithm using logarithms, and someone else said, it's faster to count the bits. After reading the bit counting algorithm several times, I realized how amazingly simple it was.
The binary number system, base 2, has two digits, 1 and 0. Every place value is a power of two (in the decimal / base 10 system, there are ten digits, 0 - 9, and every place value is a power of 10). What this means is, if only one bit is 1 in the byte (a byte is 8 bits) storing the number, it must be a power of two.
For example:
Binary Place value: From right to left, 2 ^ 0, 2 ^ 1, 2 ^ 2, etc. 128 64 32 16 8 4 2 1 1 0 0 0 0 0 0 0 The binary byte, 10000000, is 128 in decimal, and 128 is 2 ^ 7.