Sign in to follow this  
kadaf

Cross platform-friendly storage of floats

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
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

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