#include using namespace std; // Function prototype void printBinary(const unsigned char val); // We will use a preprocessor MACRO to save typing // This macro will print the specified string, followed by the // binary representation of an expression and then a newline. // The '\' simply means to continue to the nest line #define PR(STR, EXPR) cout << STR; printBinary(EXPR); cout << endl; int main() { // Make all the variables unsigned, as you do not want signs // when dealing with bits. unsigned int getval; unsigned char a, b; cout << "Enter a number between 0 and 255: "; cin >> getval; a = getval; // convert the int to it's ASCII value 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); } ///:~ // This function takes as single byte and displays it bit-by-bit void printBinary(const unsigned char val) { for(int i = 7; i >= 0; i--) if(val & (1 << i)) cout << "1"; else cout << "0"; } ///:~