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).
Knowing that the sizeof(float) is 32 bits may be sufficient, in general, but insufficient in all cases. IEEE 758 defines the well known 32-bit binary32 which is commonly implemented. But IEEE 758 also defines a 32-bit decimal32, which is primarily use for storage and not computation.
32-bit variables have a floating point value of +/-1.175494351e-38 to +/-3.402823466e+38 and 0. You can use up to 7 decimal places. 64-bit variables have a floating point value of +/-2.2250738585072014e-308 to +/-1.7976931348623158e+308 and 0. You can use up to 15 decimal places.
For example float32_t denotes a single-precision floating-point type with approximately 7 decimal digits of precision (equivalent to binary32 in IEEE_floating_point). Floating-point types in C and C++ are specified to be allowed to have (optionally) implementation-specific widths and formats.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With