Network/Host byte ordering and bitfields

Eljay Love-Jensen eljay@adobe.com
Wed Jun 23 20:54:00 GMT 2004


Hi Marcio,

I'm well versed in the issues you are hitting upon.

Are you using C or C++?

The solution is similar in C and C++, but C++ allows encapsulation so the 
implementation (from an outside perspective) may seem a little cleaner.

In either case, I recommend saving your "unsigned int a : 1" into it's very 
own byte.  Save "unsigned int b : 26" into 4 bytes (in network order in 
your serialized persistent store canonical file).  And save your "unsigned 
int c : 3" in its very own byte.

What you'll be writing are two routines:  a serializing "write" (memory to 
store) and marshalling "read" (store to memory).  In C they'll be two 
standalone routine named "writeStructA(FILE* out, struct A* x);" and 
"readStructA(FILE* in, struct A* x);".  For C++, you'll add two member 
methods, "write(std::ostream&)" and "read(std::istream&)".

Once you let me know the C or C++ question, I can provide a more complete 
short example using your struct A.

--Eljay



More information about the Gcc-help mailing list