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
-
|B31....B25 |B24....B16
|B15....B8 |B7....B0
| Big endian
-
|B7....B0 ||B15....B8
||B24....B16||B31....B25 | Little
endian
-
|b1[0],b2[7:1] | b2[0], b3[6:0] | b4[7:0]
| b5[6:0] , b6[0]| physical layout when bigend generates.
Mapping the bit fields to memory:
-
Big endian.. .b1 is the most significant bit in memory
-
For little endian i think that b1 is interpretted as the least significant
bit in memory. This would be byte 0 B0.
-
So things should almost work except that for the little endian:
-
b1 is mapped to B7, not B0. flipping the
-
b2[0] gets mapped to B15 not B8
The easiest thing would be to byte swap the data bytes. This won't work
because the little endian bit field wants the first bit field close to
the front of the first byte.
Convert big endian to little endian.
-
bit flip each 8 bit byte of the structure.
-
The bit field elements will now extract the correct bits of data, but they
are in the reverse order.
-
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:
-
byte swap the 4 bytes.
-
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