C++ 如何在C中将字节数组转换为double?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8703047/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert a byte array into double in C?
提问by beta
I've got a byte array containing 8 bytes and would like to convert and use them as a double precision binary floating-point number.
我有一个包含 8 个字节的字节数组,并希望将它们转换并用作双精度二进制浮点数。
Could someone please tell me how to convert it?
有人可以告诉我如何转换它吗?
回答by Adam Zalcman
Try this:
尝试这个:
double a;
memcpy(&a, ptr, sizeof(double));
where ptr
is the pointer to your byte array. If you want to avoid copying use a union, e.g.
ptr
指向您的字节数组的指针在哪里。如果你想避免复制使用联合,例如
union {
double d;
char bytes[sizeof(double)];
} u;
// Store your data in u.bytes
// Use floating point number from u.d
回答by ouah
Here is one solution using memcpy
function:
这是使用memcpy
函数的一种解决方案:
double d = 0;
unsigned char buf[sizeof d] = {0};
memcpy(&d, buf, sizeof d);
Note that a solution like:
请注意,解决方案如下:
d = *((double *) buf);
shoud be avoided. This is undefined behavior because it potentially violates alignment and aliasing rules.
应该避免。这是未定义的行为,因为它可能违反对齐和别名规则。
回答by Kerrek SB
In C++:
在 C++ 中:
double x;
char buf[sizeof(double)]; // your data
#include <algorithm>
// ...
std::copy(buf, buf + sizeof(double), reinterpret_cast<char*>(&x));
In C:
在 C:
#include <string.h>
/* ... */
memcpy(&x, buf, sizeof(double));
In C++11, you can also use std::begin(buf)
and std::end(buf)
as the boundaries (include the header <iterator>
), and in both languages you can use sizeof(buf) / sizeof(buf[0])
(or simply sizeof(buf)
) for the size, all provided buf
is actually an array and not just a pointer.
在 C++11 中,您还可以使用std::begin(buf)
andstd::end(buf)
作为边界(包括 header <iterator>
),并且在两种语言中您都可以使用sizeof(buf) / sizeof(buf[0])
(或简单地sizeof(buf)
)作为大小,所有提供buf
的实际上是一个数组而不仅仅是一个指针。