Jump to content
  • Advertisement
Sign in to follow this  
kadaf

Cross platform-friendly storage of floats

This topic is 4443 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

Hello. Until now I thought I could just save my floats like this:
write_LE_int(*((int *)&some_float_var));
and read them back like this:
some_int_var = read_LE_int();
some_float_var = *((float *)&some_int_var));
where write_LE_int() and read_LE_int() are methods for writing little-endian ints. While the above code works fine (at least for me) on all x86 and PPC platforms I've tried (windows, linux and mac os x), I've found out it doesn't work (at least for me) on AMD64 linux. I know there's other cross-platform'ish problems with this, including the fact that sizeof(int) might not equal sizeof(float). Ideally I want to be able to load vertex buffers directly from disk and feed them to the GPU, but I guess that isn't possible. So my question is, what is the closest thing I can get? Or in other words, what is the current best practice, when it comes to storing floats in binary data files? I know there's obscure way to do it, like storing floats in my own custom floating point format, but I'd like to be more elegant than that. Sorry for this rather confused post, but that's just because I'm confused :)

Share this post


Link to post
Share on other sites
Advertisement
Create a byte swapper that can handle general types of different sizes (2, 4, 8, ...) and read/write float through that. A single precision float is always 4 bytes (assuming all your platforms use the same floating point format (IEEE 754?)).
The byte swapper itself does not need to know the exact type, it only needs a void* buffer and the size of the current type.
[edit]
A suggestion. Create your own types with 'typedef' that have the correct size on all platforms and only use them in your code.
ie: int32, int64, float32, ...

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
and if you aren't into designing and creating your own wrappers, you might just as well settle for the serialization capabilities that libraries such as boost offer, of course this is only an option if you don't mind this non-trivial dependency.

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.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!