Advertisement
rockdrilla

int bit fields

Nov 5th, 2015
452
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.53 KB | None | 0 0
  1. #include <iostream>
  2. #include <iomanip>
  3.  
  4. using namespace std;
  5.  
  6. typedef union _test {
  7.     unsigned int h;
  8.     struct {
  9.         unsigned int f : 1, e : 8, m : 23;
  10.     } s;
  11. } test;
  12.  
  13. template <typename T>
  14. void dump_hex(const T * ptr) {
  15.     unsigned char * z = reinterpret_cast<unsigned char*>(const_cast<T*>(ptr));
  16.  
  17.     for (size_t i = 0; i < sizeof(T); ++i) {
  18.         if (i != 0) cout << " ";
  19.                 cout << "0x" << hex << (z[i] >> 4) << (z[i] & 0x0F);
  20.     }
  21. }
  22.  
  23. template <typename T>
  24. void dump_bin(const T & val, unsigned int len = 8 * sizeof(T)) {
  25.     unsigned long long x = val;
  26.  
  27.     for (unsigned int i = 0; i < len; ++i) {
  28.         cout << (x & 1);
  29.         x >>= 1;
  30.     }
  31. }
  32.  
  33. void dump(const test & val) {
  34.         cout << "0x" << setw(8) << setfill('0') << hex << val.h << endl;
  35.  
  36.         dump_hex(&val); cout << endl;
  37.  
  38.         dump_bin(val.s.f, 1);  cout << " ";
  39.         dump_bin(val.s.e, 8);  cout << " ";
  40.     dump_bin(val.s.m, 23); cout << endl;
  41.  
  42.     cout << endl;
  43. }
  44.  
  45. int main()
  46. {
  47.     test z;
  48.  
  49.     z.h = 0;
  50.     z.s.f = 1;
  51.     dump(z);
  52.     /*
  53.      * output:
  54.      * 0x00000001
  55.      * 0x01 0x00 0x00 0x00
  56.      * 1 00000000 00000000000000000000000
  57.      */
  58.  
  59.     z.h = 0;
  60.     z.s.e = 255;
  61.     dump(z);
  62.     /*
  63.      * output:
  64.      * 0x000001fe
  65.      * 0xfe 0x01 0x00 0x00
  66.      * 0 11111111 00000000000000000000000
  67.      */
  68.  
  69.     z.h = 0x12345678;
  70.     dump(z);
  71.     /*
  72.      * output:
  73.      * 0x12345678
  74.      * 0x78 0x56 0x34 0x12
  75.      * 0 00111100 11010100010110001001000
  76.      */
  77.  
  78.     return 0;
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement