Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ ensuring a float size of 4 bytes

I need a cross-architecture way to ensure that a float will be 4 bytes (as is on 32-bit windows). For instance, in the structs I'm creating, I'm using __int32 instead of int to ensure an integer value that is 4 bytes long.

How could I do this with a float? I know that I can just substitute the value with an __int32 type; however, when casting to a float on 64-bit systems, won't I have issues?

like image 860
Qix - MONICA WAS MISTREATED Avatar asked Jul 16 '12 02:07

Qix - MONICA WAS MISTREATED


1 Answers

I need a cross-architecture way to ensure that a float will be 4 bytes

There is no analog to int32_t for floating-point values.

The only cross-platform way to achieve what you want is to test for it with either runtime or static asserts.

#include <cassert>
int main () {
    assert(sizeof(float) == 4);
    // If control reaches this line, then you've 
    // ensured that float is 4 bytes.


    // rest of your program goes here
}
like image 115
Robᵩ Avatar answered Oct 05 '22 17:10

Robᵩ