从无符号字符数组转换为双精度

Convert from unsigned char array to double

本文关键字:双精度 转换 数组 无符号 字符      更新时间:2023-10-16

我将一个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行代码&张贴结果。