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?

有帮助吗?

解决方案

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
}

其他提示

There isn't a standard compliant way to do this because floating point data size is tied to the CPU. The IEEE-754 standard (which all processors that support floating point use to my knowledge) defines a single-precision floating point value as 4-bytes.

The reason why there isn't a standard mention is because the writers of C don't want to tie themselves to a specific implementation of floating point, in case the standard changes or is updated. And also because the CPU determines the sizes of and implementation of single and double precision floats anyway, so it's not something that the compiler concern itself with.

If you're worried about it, you can use a static_assert to ensure that sizeof(float) == 4; however, this isn't a problem you're going to run into I wouldn't imagine. And if it is you should deal with it on a case-by-case basis (which is really going to be an architecture-by-architecture basis.)

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top