C ++声明独立于平台的32位浮点数 [英] C++ declare platform independent 32-bit float
问题描述
有没有一种方法可以在C ++中声明32位浮点值-确保无论平台/编译器如何,它始终为32位?
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
是特定于实现的,并且不是一定是32位..(如果我错了,请纠正我)。
is implementation specific, and is not necessarily 32 bit.. (Correct me if I am wrong).
我正在使用qt,因此,如果有使用它的解决方案,我将接受它-我找不到类似quint16的float(qreal会根据平台更改大小) )。
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).
推荐答案
您正在使用Qt。
据我所知,在支持Qt的所有平台上,键入 float
是32位IEEE。
As far as I know, on all platforms where Qt is supported, type float
is 32-bit IEEE.
如果有人决定将Qt移植到具有64位的Cray向量机上位 float
,无论如何您都不会拥有32位浮点类型(除非您自己在软件中实现它,但我不知道如何实现)会很有用)。
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).
没有< stdfloat.h>
/ < ; cstdfloat>
对应于< stdint.h>
/ < cstdint>
。 C和C ++提供 float
, double
和 long double
,并且对它们施加了最低要求,但是并没有给您提供要求任何特定大小的浮点类型的方法。
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.
您最好的选择可能是在 main
或保证在程序启动期间调用的某些函数中添加以下内容:
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);
也许还有 CHAR_BIT == 8
assert
不太可能触发,并且如果触发, ,您会遇到更大的问题。
It's unlikely that the assert
will ever fire -- and if it does, you've got bigger problems.
您可能想重新考虑是否真的需要32位浮点类型。如果您的代码在具有64位 float
的系统上运行,那怎么会不能满足您的要求?
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?
这篇关于C ++声明独立于平台的32位浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!