#include #include using namespace std; unsigned powerOf2(int exp); template void printBits(T type); int main() { unsigned char a; unsigned char b; // turn a bit on a = 34; cout << " a =";printBits(a); b= 4; cout << " b =";printBits(b); cout << "a|=b"; printBits(a|=b); cout << endl; // turn a bit off a = 34; cout << " a =";printBits(a); b= 2; cout << " b =";printBits(b); cout << "a&~b"; printBits(a&~b); cout << endl; // toggle a bit a = 34; cout << " a =";printBits(a); b= 66; cout << " b =";printBits(b); cout << "a^=b"; printBits(a^=b); cout << endl; // test to see if a bit is turned on a = 34; cout << boolalpha; cout << " a =";printBits(a); cout << " 2 =";printBits(2); cout << "a & 2 = " << static_cast(a & 2) << endl; cout << " 4 =";printBits(4); cout << "a & 4 = " << static_cast(a & 4) << endl; } template void printBits(T t) { unsigned mask; unsigned char* ptr; cout << setw(5) << static_cast(t) << " "; for (size_t i = 0; i < sizeof(T); i++) { // Advance ptr each byte of the argument ptr = reinterpret_cast(&t) + i; // Print the contents of the byte for (int i = 7; i >= 0; --i) { mask = powerOf2(i); cout << (*ptr & mask ? 1 : 0); } cout << " "; } cout << endl; } unsigned powerOf2(int exp) { unsigned value = 1; for (int i = 0; i < exp; ++i) { value *= 2; } return value; }