如何在C++中将无符号字符缓冲区转换为双精度?

How do I convert an unsigned char buffer to a double in C++?

本文关键字:转换 缓冲区 双精度 字符 无符号 C++      更新时间:2023-10-16

我正在尝试将unsigned char缓冲区数组转换为双精度数组。 为什么这不会像在数组中那样将字节复制到双精度中?

#include <iostream>
#include <string>
int main() {
unsigned char buffer[8] = {63, 240, 0, 0, 0, 0, 0, 0};
double x = *(double*)buffer;
std::cout << x << std::endl;
return 0;
}

我也尝试这样做:

#include <iostream>
#include <string>
int main() {
unsigned char buffer[8] = {63, 240, 0, 0, 0, 0, 0, 0};
double x ;
memcpy(&x, buffer, sizeof(double)); //NOW USING MEMCPY
std::cout << x << std::endl;
return 0;
}

我在这里看了这篇文章,但它只得到了相同的结果。 无符号字符 {63, 240, 0, 0, 0, 0, 0, 0} 是双精度数1的表示形式。

它输出:3.03865e-319

你的缓冲区用错了。 它应该是:

{0, 0, 0, 0, 0, 0, 240, 63}

(在使用 IEEE 浮点的小端计算机上(。

现场演示