Reputation: 39354
I was recently integrating two applications running on different hardware architectures - among the problems that came up were network-byte-ordering issues and structure padding issues.
Both were easy enough to fix - for the padding specifically, I just had to add pragmas around my networking structs as so:
#pragma pack(1)
struct {};
#pragma pack(0)
I saw a couple of questions relating to bitfields yesterday though which I have never used. I was wondering... would it have been more right to try and stop the padding by defining the structs using bitfields? Would that have helped at all in this scenario?
Also, I haven't run into bitfields much in C++ code - are they more of a C thing that isn't used as much or have I just happened to work on code that doesn't use them?
Upvotes: 0
Views: 1142
Reputation: 400139
No, bitfields are a horrible choice for external representations, such as network packet definitions. It's completely up to the compiler to select the layout in memory of the bitfield (in which way bits are ordered, how many bytes are reserved for a given field, and so on), so you absolutely kill interoperability.
That said, I'm opposed using "naked" structures for this as well, for the reasons you've run into.
In my view, the proper way is to serialize/de-serialize the fields one by one, manually.
Upvotes: 3