home *** CD-ROM | disk | FTP | other *** search
/ Reverse Code Engineering RCE CD +sandman 2000 / ReverseCodeEngineeringRceCdsandman2000.iso / RCE / Ebooks / Thinking in C++ V2 / C03 / Bitwise.cpp < prev    next >
Encoding:
C/C++ Source or Header  |  2000-05-25  |  1.1 KB  |  47 lines

  1. //: C03:Bitwise.cpp
  2. // From Thinking in C++, 2nd Edition
  3. // Available at http://www.BruceEckel.com
  4. // (c) Bruce Eckel 1999
  5. // Copyright notice in Copyright.txt
  6. // Demonstration of bit manipulation
  7. #include <iostream>
  8. using namespace std;
  9.  
  10. // Display a byte in binary:
  11. void printBinary(const unsigned char val) {
  12.   for(int i = 7; i >= 0; i--)
  13.     if(val & (1 << i))
  14.       cout << "1";
  15.     else
  16.       cout << "0";
  17. }
  18.  
  19. // A macro to save typing:
  20. #define PR(STR, EXPR) \
  21.   cout << STR; printBinary(EXPR); cout << endl;  
  22.  
  23. int main() {
  24.   unsigned int getval;
  25.   unsigned char a, b;
  26.   cout << "Enter a number between 0 and 255: ";
  27.   cin >> getval; a = getval;
  28.   PR("a in binary: ", a);
  29.   cout << "Enter a number between 0 and 255: ";
  30.   cin >> getval; b = getval;
  31.   PR("b in binary: ", b);
  32.   PR("a | b = ", a | b);
  33.   PR("a & b = ", a & b);
  34.   PR("a ^ b = ", a ^ b);
  35.   PR("~a = ", ~a);
  36.   PR("~b = ", ~b);
  37.   // An interesting bit pattern:
  38.   unsigned char c = 0x5A; 
  39.   PR("c in binary: ", c);
  40.   a |= c;
  41.   PR("a |= c; a = ", a);
  42.   b &= c;
  43.   PR("b &= c; b = ", b);
  44.   b ^= a;
  45.   PR("b ^= a; b = ", b);
  46. } ///:~
  47.