[英]C++ double pointer array to float conversion
What is a correct way to convert double to float in c++. 在c ++中将double转换为float的正确方法是什么。 Is the conversion implicit?
转换是隐式的吗?
Question 1: Consider double d = 5.0;
问题1:考虑
double d = 5.0;
and float f;
并
float f;
Which one is correct? 哪一个是正确的?
f = d;
f = (float)d;
f = static_cast<float>(d);
Question 2: Now consider we have 问题2:现在考虑
char *buffer = readAllBuffer();
double *d = (double*)(buffer + offset);
float f;
Which one is now correct? 现在哪一个是正确的?
f = d[0];
f = (float)d[0];
f = static_cast<float>(d[0]);
Thanks in advance! 提前致谢!
They all boil down to the same thing, and the use of arrays is a red herring. 他们全都归结为同一件事,而使用数组是一个红鲱鱼。 You can indeed write
你确实可以写
float f = d;
Some folk argue that a static_cast
makes code more readable as it sticks out so clearly. 一些人认为,
static_cast
突出之处在于使代码更具可读性。 It can also defeat warnings that some compilers might issue if a less long-winded form is used. 如果使用的格式不那么冗长,它也可以消除某些编译器可能发出的警告。
Naturally of course since a double
is a superset of float
, you might lose precision. 当然,由于
double
是float
的超集,因此您可能会失去精度。 Finally, note that for 最后,请注意
float f1 = whatever;
double d1 = f1;
float f2 = d1;
, the C++ standard insists that f1
and f2
must be the same value. ,C ++标准坚持认为
f1
和f2
必须具有相同的值。
You do have one major issue. 您确实有一个主要问题。 This is not allowed:
这是不允许的:
double *d = (double*)(buffer + offset);
It violates strict aliasing and quite possibly alignment requirements. 它违反了严格的混叠和可能的对齐要求。 Instead you need to use
memcpy
: 相反,您需要使用
memcpy
:
double d;
memcpy(&d, buffer + offset, sizeof d);
float f = d;
Either of the cast alternative can be substituted for the last line, the important change is from dereferencing an pointer with incorrect type and alignment to making a bytewise copy. 可以使用任何一种强制转换选项替代最后一行,重要的变化是从取消引用类型和对齐方式不正确的指针到进行字节复制。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.