#include #include #include using namespace std; unsigned powerOf2(int exp); template void printBits(T type); int main() { unsigned char a = 77; unsigned char b = 20; cout << " a =";printBits(a); cout << " b =";printBits(b); cout << "a&b =";printBits(a&b); cout << "a|b =";printBits(a|b); cout << "a^b =";printBits(a^b); cout << " ~a =";printBits(~a); cout << "a<<1=";printBits(a<<1); cout << "a<<2=";printBits(a<<2); cout << "a<<8=";printBits(a<<8); cout << "a<<9=";printBits(a<<9); cout << "a>>1=";printBits(a>>1); cout << "a>>2=";printBits(a>>2); cout << "a>>9=";printBits(a>>9); } 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; }