Search code examples
cstructbit-fields

How to display the bit pattern of a Structure variable in C which uses bit fields?


    Struct some{
         unsigned int a:5;
         Unsigned int b:6;
    } std1;

Now let us have stored some values in std1. Now how can we display the bit pattern of the structure variable std1 in C?


Solution

  • For any data type in C, you can inspect its raw binary contents by iterating over it using character type pointers. Example:

    const uint8_t* ptr = (const uint8_t*)&std1;
    for(size_t i=0; i<sizeof std1; i++)
    {
      printf("%.2X ", (unsigned int)ptr[i]);
    }
    

    (uint8_t will always be a character type in all real world systems except on some dysfunctional legacy DSPs that shouldn't be used for any purpose.)