Sign in to follow this  
Guy Meh

Binary writing/reading and stdint

Recommended Posts

Guy Meh    122
I've been thinking about how I'm going to write my save files. Suppose I have a class with some variables, such as a couple of integers. If I want to write the data in this class to a file and be able to read it back to rebuild the class later, I'd want to be sure that the variables are stored in fixed sizes (like an int always being 32 bytes or something). I've read about stdint.h, and I've also (finally!) installed Boost, which has its own version of stdint.h. For my class whose data I want to serialize, would I have to define its variables using the fixed-size types or could I simply cast its variables while writing? In other words, do I require this:
class MyClass
{
    ...
    int32_t myValue;
};
...or can myValue be a regular int which I cast to an int32_t while reading and writing?

Share this post


Link to post
Share on other sites
Brother Bob    10344
I suggest you keep your internal values at native types and use fixed sizes only where you need them. So store an int in the class, and make a function to read a 32-bit integer from file and return it as an int no matter what the actual size of it is. This solves endian issues also. With this, you have separated internal and external storage, and you are pretty much independent on what the system actually is.

Share this post


Link to post
Share on other sites
Guy Meh    122
That's kind of what I wanted to hear. I had a bunch of code and I didn't want to have to go back and change all those int's into int32_t's.

For writing an int, is a cast all I need? Like this:

ofstream file;
int myVal;

...

int32_t tempMyVal = (int32_t)myVal;
file.write(reinterpret_cast<char *>(tempMyVal), sizeof(tempMyVal));

Share this post


Link to post
Share on other sites
Brother Bob    10344
Like that, yes. The value you have in native storage is stored in a 32-bit for saving, and then you save that. You can also, if you need protection against endianness, save each byte in a specific order (lower to higher, or the other way around, as you like).

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this