-
portable bitfields
I want to make some portable bitfield for writing to a file, however from what I've read they are very unprotable and have no address. So I was thinking that maybe seperate structers for each bitfield type would fix that problem.
Code:
struct sMyVar {
unsigned field :4;
};
sMyVar myVar;
So would a pointer to myVar unltimitaly point to my half byte? Also, would writting 2 of them to a file end of being a complete byte, or a two bytes, half of each of which are blank?
-
The problem is, if you try to write myVar to a file, you're going to get all the invisible padding bits as well. Any operation you try on the whole structure will always get all the padding as well.
Also, there isn't a sure way of knowing what underlying data type the compiler chooses to store bit-fields in. So sizeof(myVar) might be sizeof(char) or sizeof(long).
Also, there is no way to know (or control) how the bit-fields are arranged. For example, your :4 field might be stored in an unsigned long with a mask of 0xF0000000 or a mask of 0x0000000F.
-
Most compilers will make a 4-bit field take up one byte, where four bits are undefined (not necessarily zero). A second 4-bit field next to it will take up another byte with four unused bits.
If you want to store 4-bit fields in a file, then you're best of making multiple 4-bit fields into a single structure (2, 4 or 8 for example). I don't think you can make arrays of bitfields - maybe you can - it would certainly make it easier.
Alternatively, just pack by hand into a 8, 16 or 32-bit integer using shifts - that will have the benefit of being more likely to be portable too - particularly if you expect this code to work on both little-endian and big-endian machines.
--
Mats