从无符号字符数组转换为双精度
Convert from unsigned char array to double
我将一个double转换为无符号char数组。例如,对于值1,数组变为{64240,0,0,0,0:0}。现在,我尝试使用以下代码将数组转换回来,但我得到的只是糟糕的值。。。
double* pdfOutput = (double*)malloc(sizeof(double));
memcpy(pdfOutput, pInputArray, sizeof(double));
你能告诉我问题出在哪里吗?谢谢
编辑:pInputArray由LabVIEW生成。基本上,我在这里试图做的是制作一个与LabVIEW VI对话的程序。所以我无法控制输入数组。。。
完成您的要求的简单方法是编写:
double pdfOutput = *(double*)pInputArray;
但这将产生与您的代码完全相同的结果。换句话说,重新解释您所拥有的char数组不会产生您所期望的双值。您需要查看char数组的来源。创建char数组的代码正是我所期望的问题所在。要解决您的问题,您需要了解LabVIEW代码在做什么。
问题在于字节的顺序(即endianness)。您可能无法简单地使用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): %fnn",
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系统上,我得到了以下结果:
原始字节:3f f0 00 00 00 00(63 240 0 0 0 0)解释为带符号的64位整数:61503解释为无符号64位整数:61503解释为双精度(具有"浮点"精度):0.000000原始字节:00 00 00 00 f0 3f(0 0 0 0 240 63)解释为带符号的64位整数:4607182418800017408解释为无符号64位整数:4607182418800017408解释为双精度(具有"浮点"精度):1.000000
我怀疑运行Visual Studio(当然是在x86上)的人也会得到同样的结果。当我在PowerPC Linux机器(也是GCC)上运行相同的程序时,我会得到以下结果:
原始字节:3f f0 00 00 00 00(63 240 0 0 0 0)解释为带符号的64位整数:4607182418800017408解释为无符号64位整数:4607182418800017408解释为双精度(具有"浮点"精度):1.000000原始字节:00 00 00 00 f0 3f(0 0 0 0 240 63)解释为带符号的64位整数:61503解释为无符号64位整数:61503解释为双精度(具有"浮点"精度):0.000000
我假设您可以将此研究转换为适合您平台的转换代码。如果我的假设不正确,请告诉我&在您的系统上运行以上程序后,我将为您编写所需的2行代码&张贴结果。
相关文章:
- 为什么将双精度转换为 int 似乎在第 16 位数字之后将其四舍五入?
- 在 c++ 中从双精度转换为字符串
- 使用 sprintf 和 %g 将双精度转换为字符串的意外结果
- 从双精度转换为整数的显式类型是否始终检查整数溢出?
- C++,遇到将双精度转换为整数的问题
- 在C++中将双精度转换为intptr_t
- 将大双精度转换为科学记数法以用作字符串?
- 了解双精度转换与整数转换中的整数与截断关系
- 将 OLE 自动化日期 (OADate) 双精度转换为结构 tm,而不使用 VariantTime到SystemTime
- 无法在赋值中将"双精度 (*)[4]"转换为"双精度**"
- 将大双精度转换为无符号 int 期间堆栈损坏
- 将双精度转换为本地8位
- 警告从"双精度"转换为"int"
- 如何将双精度转换为浮点指针
- 将双精度转换为整数时出错
- 使用并集将双精度转换为十六进制再转换为双精度
- 是否有可以将每个双精度转换为唯一uint64_t,保持精度和顺序的功能?(为什么我找不到?
- 使用定点表示法将双精度转换为字符串,没有尾随零和机智的冲刺
- 在C++中将双精度转换为字符*/字符串
- 无法将双精度 [] [] 转换为双精度 **