Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <iomanip>
- using namespace std;
- typedef union _test {
- unsigned int h;
- struct {
- unsigned int f : 1, e : 8, m : 23;
- } s;
- } test;
- template <typename T>
- void dump_hex(const T * ptr) {
- unsigned char * z = reinterpret_cast<unsigned char*>(const_cast<T*>(ptr));
- for (size_t i = 0; i < sizeof(T); ++i) {
- if (i != 0) cout << " ";
- cout << "0x" << hex << (z[i] >> 4) << (z[i] & 0x0F);
- }
- }
- template <typename T>
- void dump_bin(const T & val, unsigned int len = 8 * sizeof(T)) {
- unsigned long long x = val;
- for (unsigned int i = 0; i < len; ++i) {
- cout << (x & 1);
- x >>= 1;
- }
- }
- void dump(const test & val) {
- cout << "0x" << setw(8) << setfill('0') << hex << val.h << endl;
- dump_hex(&val); cout << endl;
- dump_bin(val.s.f, 1); cout << " ";
- dump_bin(val.s.e, 8); cout << " ";
- dump_bin(val.s.m, 23); cout << endl;
- cout << endl;
- }
- int main()
- {
- test z;
- z.h = 0;
- z.s.f = 1;
- dump(z);
- /*
- * output:
- * 0x00000001
- * 0x01 0x00 0x00 0x00
- * 1 00000000 00000000000000000000000
- */
- z.h = 0;
- z.s.e = 255;
- dump(z);
- /*
- * output:
- * 0x000001fe
- * 0xfe 0x01 0x00 0x00
- * 0 11111111 00000000000000000000000
- */
- z.h = 0x12345678;
- dump(z);
- /*
- * output:
- * 0x12345678
- * 0x78 0x56 0x34 0x12
- * 0 00111100 11010100010110001001000
- */
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement