I always wanted to write a library to write and read simple data types ( integers, floats, etc. ) to/from files. Also, I wanted the library to be as much cross-platform as it can be - if I write an integer to a file on Mac, I want to get the same number from that file on Windows.
I've actually written that library, but I feel I've made an overkill with it. It's designed to handle little-endian data. It gives you a buffer class, to which you can write integers, floats, or just random blobs of data. The overkill I mentioned happens when writing specific data formats. It constructs everything bit-by-bit, eg.:
buffer& operator<<(buffer& os, unsigned short x)
{
if(os.size()<os.tellp()+2){os.resize(os.size()+2);}
size_t offs=os.tellp()*8; //Bit index to start writing at
for(byte_t i=0; i<16; i++){os.set_bit(offs+i,(x>>i)&1);}
os.seekp(2,1);
return os;
};
I'm suspecting I could do something like this:
buffer& operator<<(buffer& os, unsigned short x)
{
os.put(x%256); x -= x%256;
os.put(x/256);
return os;
};
And it would be still readable on most of the platforms.
So my questions:
- If I handle bytes instead of bits, will it still be readable on other platforms? Or on other computers?
- With the simplified method, how would I go with signed integers? Use it's abs but write inverted bytes? ( ~x operator )
- Floats?
Also, a note: Another concern while writing this library to conform to some kind of standard. So, for integers, I've just checked how Window's calc.exe handles them, for floats, I checked Wikipedia ( http://en.wikipedia.org/wiki/Single-precision_floating-point_format )
You can check the whole source at https://github.com/elementbound/binio. The interesting parts are binio/buffer.h ( buffer class ) and binio/formats.h and .cpp.