Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Is there a way to declare 32-bit floating point value in C++ - ensuring that it will always be 32 bits regardless of platform/compiler?

I can do that for integers like that:

#include <stdint.h>

uint32_t var;  //32 bit unsigned integer
uint64_t var1; //64 bit unsigned integer

is there a way to do something like that for floats? As far as I know,

float var; //Usually is 32 bit, but NOT GUARANTEED to be 32 bit

is implementation specific, and is not necessarily 32 bit.. (Correct me if I am wrong).

I am using qt, so if there is any solution using it I would accept it - I couldn't find anything like quint16 for floats (qreal changes size depending on platform).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
849 views
Welcome To Ask or Share your Answers For Others

1 Answer

You're using Qt. which is specific to C++, so I'm not sure why the question is tagged C.

As far as I know, on all platforms where Qt is supported, type float is 32-bit IEEE.

If somebody decides to port Qt to, say, a Cray vector machine with 64-bit float, you're not going to have a 32-bit floating-point type anyway (unless you implement it yourself in software, but I don't see how that would be useful).

There is no <stdfloat.h> / <cstdfloat> corresponding to <stdint.h> / <cstdint>. C and C++ provide float, double, and long double, and imposes minimal requirements on them, but doesn't give you a way to ask for a floating-point type of any specific size.

Your best bet is probably to add something like this in main, or in some function that's guaranteed to be called during program startup:

assert(CHAR_BIT * sizeof (float) == 32);

and perhaps CHAR_BIT == 8 as well if your code implicitly depends on that.

It's unlikely that the assert will ever fire -- and if it does, you've got bigger problems.

You might want to reconsider whether you really need a 32-bit floating type. If your code were running on a system with 64-bit float, how would that fail to meet your requirements?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...