home *** CD-ROM | disk | FTP | other *** search
- //: C03:Bitwise.cpp
- // From Thinking in C++, 2nd Edition
- // Available at http://www.BruceEckel.com
- // (c) Bruce Eckel 1999
- // Copyright notice in Copyright.txt
- // Demonstration of bit manipulation
- #include <iostream>
- using namespace std;
-
- // Display a byte in binary:
- void printBinary(const unsigned char val) {
- for(int i = 7; i >= 0; i--)
- if(val & (1 << i))
- cout << "1";
- else
- cout << "0";
- }
-
- // A macro to save typing:
- #define PR(STR, EXPR) \
- cout << STR; printBinary(EXPR); cout << endl;
-
- int main() {
- unsigned int getval;
- unsigned char a, b;
- cout << "Enter a number between 0 and 255: ";
- cin >> getval; a = getval;
- PR("a in binary: ", a);
- cout << "Enter a number between 0 and 255: ";
- cin >> getval; b = getval;
- PR("b in binary: ", b);
- PR("a | b = ", a | b);
- PR("a & b = ", a & b);
- PR("a ^ b = ", a ^ b);
- PR("~a = ", ~a);
- PR("~b = ", ~b);
- // An interesting bit pattern:
- unsigned char c = 0x5A;
- PR("c in binary: ", c);
- a |= c;
- PR("a |= c; a = ", a);
- b &= c;
- PR("b &= c; b = ", b);
- b ^= a;
- PR("b ^= a; b = ", b);
- } ///:~
-