Breaking a float into bytes for binary I/O

closed account (N36fSL3A)
Hello, I'd like to know how I could break a float into individual bytes for binary use.

Sounds simple, but it seems as though the compiler doesn't realize everything is just a series of bytes.

Thanks in advance.
You don't need individual bytes. Here is an example with saving to a file:
1
2
3
4
5
6
{
    std::ofstream out ("out.dat");
    float a = 3.14;
    double b = 3.1415926;
    out.write((char const *)&a, sizeof(a)).write((char const *)&b, sizeof(b));
}
Last edited on
closed account (N36fSL3A)
But is that cross platform?
Using floats and doubles in the first place is not cross-platform. Different hardware handles floats and doubles differently. What specifically are you concerned about?
Last edited on
closed account (N36fSL3A)
The thing is I'm using this for my 3D model format. I don't want my data to be read wrong.

Endians aren't a problem.
If endianess isn't an issue I don't see what you're worried about ;)
closed account (N36fSL3A)
Oh, thanks :D But how would I read them?
Last edited on
I'll have both the write and read code:

Writing:
1
2
3
4
5
6
{
    std::ofstream out ("floats.dat");
    float a = 3.14;
    double b = 3.1415926;
    out.write((char const *)&a, sizeof(a)).write((char const *)&b, sizeof(b));
}
Reading:
1
2
3
4
5
6
{
    std::ifstream in ("floats.dat");
    float a;
    double b;
    in.read((char *)&a, sizeof(a)).read((char *)&b, sizeof(b));
}
closed account (N36fSL3A)
Thanks.
Topic archived. No new replies allowed.