Bitfield storage in memory

may 2006

    Bit field are structures in c that hold bit fields. A typical definition is:
 
typedef struct {
    unsigned int    b1:1;
    unsigned int    b2:8;
    unsigned int    b3:7;
    unsigned int    b4:8;
    unsigned int    b5:7;
    unsigned int    b6:1;} BIT_STRUCT;


    Suppose you wanted to use the same structure definition to read in bit field data on an
big endian and little endian machine and you were willing to massage the data on input
before mapping the structure to it. Suppose we started with big endian data that was
32 bits long.


Memory layout big/little endian:

Let the start of memory be adressed as below for a big endian machine...

              byte 0          byte 1       byte 2       byte 3


Mapping the bit fields to memory:


Convert big endian to little endian.

  1. bit flip each 8 bit byte of the structure.
  2. The bit field elements will now extract the correct bits of data, but they are in the reverse order.
  3. bit flip each of the structure elements. This needs to be done knowing how many bits each element uses. You can't transfer to a long , flip and then reassign. So you are stuck needing to know the length of each field (unfortunately only the compiler knows that).
Another way to do it would be to:
  1. byte swap the 4 bytes.
  2. use the shift and mask operations to peel away Nbits at a time starting at the right side. This also needs to know the length of each structure element.


home_~phil