/* ************************************************************************** * Program name : 059_Bitwise_Operations (Version 1.00) * * Author : Duck Wong * * Language : C / C++ * * Compiler : Boodshed Dec-C++ compiler Ver 3.95 * * Computer : PII350 * * O/S : Windows 98 * ************************************************************************** * Version 1.00 : 2001/02/09 - first version * ************************************************************************** * Description : (a) show basic function of bitwise operators * * (b) express an integer number in binary format * * (c) Try again ? * ************************************************************************** */ #include #include int main() { // part 1 : declaration char Again; do { // part 2 : Example 1 int a,b; a = b= 0; do { cout << "\n\tPlease input an integer number (1 to 256): "; cin >> a; } while ((a <1) || (a>256)); do { cout << "\n\tPlease inout another integer number (1 to 256): "; cin >> b; } while ((b <1) || (b>256)); cout << "\n\tThen the result of different bitwise operations are\n" << "\t---------------------------------------------------\n" << "\tOperators Result Meaning\n" << "\t a & b " << (a&b) << " \tAND\n" << "\t a | b " << (a|b) << " \tOR\n" << "\t a ^ b " << (a^b) << " \tExclusive OR\n" << "\t a << b " << (a<> b " << (a>>b) << " \tRight-shift by 3 bits\n" << "\t ~a " << (~a) << " \tOnes complement\n" << "\t---------------------------------------------------" << endl; // part 3 : Example 2 , express an integer number in binary pattern int c,d; c = d= 0; do { cout << "\n\tPlease input an integer number (1 to 256): "; cin >> c; } while ((c <0) || (c>255)); cout << "\n\t" << c << " equals to : "; for (d=7;d>=0;d--) {cout << (c>>d & 1);} cout << " in base 2. " <> Again; cout << "\n"; } while (Again=='Y' || Again=='y'); cout << "\n" << endl; system("PAUSE"); return 0; } /* Notes (1) Example : Let a = 10 and b = 3, then a = 1010 & b = 11 in base 2 so that : Operators Result Values in base 2 Meaning a & b 2 10 AND a | b 11 1011 OR a ^ b 9 1001 exclusive OR a << b 80 1010000 left-shift by 3 bits a >> b 1 right-shift by 3 bits ~a -11 Ones complement */