I have a numerous small pieces of data that I want to be able to shove into one larger data type. Let\'s say that, hypothetically, this is a date and time. The obvious method is
Depends. If you use bit fields, then you let the compiler worry about how to store the data (bitfields are pretty much completely implementation-defined), which means that:
The compiler will typically organize the layout of the struct so that the second assumption holds, at the cost of total size of the struct.
The compiler will probably insert padding between each member, to ease access to each field.
On the other hand, if you just store everything in a single unsigned long
(or an array of chars), then it's up to you to implement efficient access, but you have a guarantee of the layout. It will take up a fixed size, and there will be no padding. And that means that copying the value around may get less expensive. And it'll be more portable (assuming you use a fixed-size int type instead of just unsigned int
).