Monday, 15 July 2013

c++ - Serializing values to a string of bytes in a platform-independent way -



c++ - Serializing values to a string of bytes in a platform-independent way -

i’m writing serialization code work @ lower level i’m used to. need functions take various value types (int32_t, int64_t, float, etc.) , shove them vector<unsigned char> in preparation beingness written file. file read , reconstituted in analogous way.

the functions write vector this:

void write_int32(std::vector<unsigned char>& buffer, int32_t value) { buffer.push_back((value >> 24) & 0xff); buffer.push_back((value >> 16) & 0xff); buffer.push_back((value >> 8) & 0xff); buffer.push_back(value & 0xff); } void write_float(std::vector<unsigned char>& buffer, float value) { assert(sizeof(float) == sizeof(int32_t)); write_int32(buffer, *(int32_t *)&value); }

these bit-shifting, type-punning atrocities seem work, on single machine i’ve used far, sense extremely fragile. can larn operations guaranteed yield same results across architectures, float representations, etc.? specifically, there safer way i’ve done in these 2 illustration functions?

a human readable representation safe. xml xsd 1 alternative can allow specify value , format.

if want binary representation, @ hton* , ntoh* functions:

http://beej.us/guide/bgnet/output/html/multipage/htonsman.html

c++

No comments:

Post a Comment