将char *转换为double - 作为字节

时间:2013-03-17 18:21:00

标签: c++ casting double c-strings

我有一个代表double的字节数组:

char number[8];

我需要将它转换为实际的double(也有8个字节)。基于我尝试过的建议,但它失败了:

std::cout<<(*((*double)number))<<" is my number.\n";

为什么会失败,我该怎么办?当然,我可以使用一些<<魔法提取数据,但我不想这样做 - 它会消耗内存并使代码过于健壮。

3 个答案:

答案 0 :(得分:8)

  

为什么会失败?

你这里有一个错字。

std::cout<<(*((*double)number))<<" is my number.\n";

应该是:

std::cout<<(*((double*)number))<<" is my number.\n";
  

我该怎么办?

可以减少使用的括号数。

std::cout<< *(double*)number <<" is my number.\n";

应该使用C ++强制转换而不是C强制转换,因此很清楚你正在做什么。

std::cout<< *reinterpret_cast<double*>(number) <<" is my number.\n";

答案 1 :(得分:3)

如果您使用c ++,请使用 reinterpret_cast 。正如你所看到的,C ++有更多的表现力。

// cool c++
double value = *reinterpret_cast<double*>(number);

// c style
double value = (*((double*)number));

答案 2 :(得分:1)

char number[8];
double d;
// number is assumed to be filled with a buffer representing a double.
memcpy(&d, &number, sizeof(double));
std::cout << d;

不确定是否需要sizeof。当假设双倍是8个字节时,已经处理了损坏。我不知道它在双打标准中的含义。

相关问题