Wednesday, September 29, 2010

C Bit packing and structs

Bit packing of a struct is achieved with the ":" after the member of the struct this little item is great for working with binary images of data however it can lead to surprises. Always keep in mind the compiled result will mask and shift every thing you place in the struct.

#include <stdint.h>
#include <iostream>

using namespace std;

typedef struct {
    uint8_t a :6;
    uint8_t b :1;
    uint8_t c :1;
} Test1;

typedef struct {
    uint8_t a;
    uint8_t b;
    uint8_t c;
} Test2;

typedef union {
    struct {
 uint8_t a :6;
 uint8_t b :1;
 uint8_t c :1;
    } bits;
    uint8_t full;
} Test3;

int main()
{
    Test3 test3;
    
    cout << sizeof(Test1) << endl;
    cout << sizeof(Test2) << endl;
    cout << sizeof(Test3) << endl;
    
    test3.bits.a = 0;
    test3.bits.b = 0;
    test3.bits.c = 0;
    
    cout << "Test3 inited:" << endl 
  << (int)test3.bits.a << endl
  << (int)test3.bits.b << endl
  << (int)test3.full   << endl;
    
    test3.bits.a = 0xff;
    
    cout << "Test3.bits.a loaded with 255:" << endl 
  << (int)test3.bits.a << endl
  << (int)test3.bits.b << endl
  << (int)test3.full   << endl;
    
    test3.bits.a = 0x0;
    test3.bits.b = 0xff;
    
    cout << "Test3.bits.b loaded with 255:" << endl 
  << (int)test3.bits.a << endl
  << (int)test3.bits.b << endl
  << (int)test3.full   << endl;
}

The output looks like this (depending on machine endianness)
1
3
1
Test3 inited:
0
0
0
Test3.bits.a loaded with 255:
63
0
252
Test3.bits.b loaded with 255:
0
1
2

No comments:

Post a Comment