Jump to content
  • Advertisement
Sign in to follow this  
Guy Meh

Binary writing/reading and stdint

This topic is 3672 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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
Advertisement
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
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
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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!