Bitwise Operators with Basic C++
Overview
The function of this program is very straightforward: it prints out three tables, which display the results of the AND, OR, and XOR bitwise operators. This is the first C++ tutorial I've put on here, and I decided on an example like this because I'm messing around with some other computer science stuff right now...so it just seemed to fit together well. You'll notice that conio.h must be included in order to use the getch(); function. Also, something that's kind of important: when using bitwise operators, you MUST include them in parenthesis. If you have "1 & 0" instead of "(1 & 0)", the compiler will freak out.
The Code
#include <iostream.h>
#include <conio.h>
int main()
{
cout << "Bit-operators example\nBy Sean Patrick Kane\nhttp://celtickane.com\n\n";
//AND operator
cout << "****AND(&)****\n";
cout << "*..A..B..A&B.*\n";
cout << "* 1 0 " << (1 & 0) << " *\n";
cout << "* 0 1 " << (0 & 1) << " *\n";
cout << "* 0 0 " << (0 & 0) << " *\n";
cout << "* 1 1 " << (1 & 1) << " *\n";
cout << "**************\n";
cout << "Hit any key to continue...\n";
getch();
//OR operator
cout << "\n****OR (|)****\n";
cout << "*..A..B..A|B.*\n";
cout << "* 1 0 " << (1 | 0) << " *\n";
cout << "* 0 1 " << (0 | 1) << " *\n";
cout << "* 0 0 " << (0 | 0) << " *\n";
cout << "* 1 1 " << (1 | 1) << " *\n";
cout << "**************\n";
cout << "Hit any key to continue...\n";
getch();
//XOR operator
cout << "\n****XOR(^)****\n";
cout << "*..A..B..A^B.*\n";
cout << "* 1 0 " << (1 ^ 0) << " *\n";
cout << "* 0 1 " << (0 ^ 1) << " *\n";
cout << "* 0 0 " << (0 ^ 0) << " *\n";
cout << "* 1 1 " << (1 ^ 1) << " *\n";
cout << "**************\n";
cout << "Hit any key to exit...\n";
getch();
return 0;
}
Code Output
After being run, you should see the following output (this assumes it runs in a console that doesn't have truetype font -- like DOS)
Bit-operators example
By Sean Patrick Kane
http://celtickane.com
****AND(&)****
*..A..B..A&B.*
* 1 0 0 *
* 0 1 0 *
* 0 0 0 *
* 1 1 1 *
**************
Hit any key to continue...
****OR (|)****
*..A..B..A|B.*
* 1 0 1 *
* 0 1 1 *
* 0 0 0 *
* 1 1 1 *
**************
Hit any key to continue...
****XOR(^)****
*..A..B..A^B.*
* 1 0 1 *
* 0 1 1 *
* 0 0 0 *
* 1 1 0 *
**************
Hit any key to exit...
Back to the Programming Index