我有一个double转换为unsigned char数组。例如,对于值1,数组变为{64,240,0,0,0,0,0,0}。现在我尝试使用以下代码将数组转换回来,但我得到的只是crapy值...
double* pdfOutput = (double*)malloc(sizeof(double));
memcpy(pdfOutput, pInputArray, sizeof(double));
请您告诉我问题在哪里?感谢。
编辑:pInputArray由LabVIEW生成。基本上我在这里要做的就是让一个程序与LabVIEW VI对话。所以我没有输入数组的控制权......
答案 0 :(得分:4)
做你要求的简单方法是写:
double pdfOutput = *(double*)pInputArray;
但这会产生与您的代码相同的结果。换句话说,重新解释您拥有的char数组不会产生您期望的double值。您需要查看char数组的来源。创建char数组的代码是我预期的问题所在。要解决您的问题,您需要了解LabVIEW代码正在做什么。
答案 1 :(得分:1)
问题是字节的顺序(即字节顺序)。您可能无法简单地使用memcpy(),具体取决于系统的字节顺序。无论如何,如果你处理单个字节,你将不得不考虑字节序...在一个系统上工作的东西不一定适用于另一个系统。
试试这个程序:
#include <stdio.h>
//typedef __int64 int64; // for Visual Studio
//typedef unsigned __int64 uint64; // for Visual Studio
typedef long long int64; // for GCC
typedef unsigned long long uint64; // for GCC
//#define PRId64 "%I64d" // for Visual Studio
//#define PRIu64 "%I64u" // for Visual Studio
#define PRIu64 "%llu" // for GCC
#define PRId64 "%lld" // for GCC
union U {
unsigned char c[8];
int64 s64;
uint64 u64;
double d;
};
void printU( U& u )
{
printf("Raw bytes: %02x %02x %02x %02x %02x %02x %02x %02x "
" (%u %u %u %u %u %u %u %u)\n"
"Interpreted as a signed 64-bit integer: "PRId64"\n"
"Interpreted as an unsigned 64-bit integer: "PRIu64"\n"
"Interpreted as a double (with 'float' precision): %f\n\n",
u.c[0], u.c[1], u.c[2], u.c[3],
u.c[4], u.c[5], u.c[6], u.c[7],
u.c[0], u.c[1], u.c[2], u.c[3],
u.c[4], u.c[5], u.c[6], u.c[7],
u.s64, u.u64, (float)u.d);
}
int main()
{
U u;
u.c[0]=63; u.c[1]=240; u.c[2]=0; u.c[3]=0;
u.c[4]=0; u.c[5]=0; u.c[6]=0; u.c[7]=0;
printU(u);
u.c[0]=0; u.c[1]=0; u.c[2]=0; u.c[3]=0;
u.c[4]=0; u.c[5]=0; u.c[6]=240; u.c[7]=63;
printU(u);
}
在我的带有GCC的x86 Linux系统上,我得到以下结果:
Raw bytes: 3f f0 00 00 00 00 00 00 (63 240 0 0 0 0 0 0) Interpreted as a signed 64-bit integer: 61503 Interpreted as an unsigned 64-bit integer: 61503 Interpreted as a double (with 'float' precision): 0.000000 Raw bytes: 00 00 00 00 00 00 f0 3f (0 0 0 0 0 0 240 63) Interpreted as a signed 64-bit integer: 4607182418800017408 Interpreted as an unsigned 64-bit integer: 4607182418800017408 Interpreted as a double (with 'float' precision): 1.000000
我怀疑有人运行Visual Studio(当然是在x86上)会得到相同的结果。当我在PowerPC Linux机器(也是GCC)上运行相同的程序时,我得到了这些结果:
Raw bytes: 3f f0 00 00 00 00 00 00 (63 240 0 0 0 0 0 0) Interpreted as a signed 64-bit integer: 4607182418800017408 Interpreted as an unsigned 64-bit integer: 4607182418800017408 Interpreted as a double (with 'float' precision): 1.000000 Raw bytes: 00 00 00 00 00 00 f0 3f (0 0 0 0 0 0 240 63) Interpreted as a signed 64-bit integer: 61503 Interpreted as an unsigned 64-bit integer: 61503 Interpreted as a double (with 'float' precision): 0.000000
我假设您可以将此研究转换为适合您平台的转换代码。如果我的假设不正确,请告诉我&amp;在您的系统上运行上述程序后,我将为您编写所需的2行代码。发布结果。