如何在C++中把一个无符号字符缓冲区转换为double?

问题描述 投票:0回答:1

我想把一个 unsigned char 缓冲区数组变成一个double.为什么这样做不能将数组中的字节复制到double中?

#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;
}

我看了这个帖子 此处但它只得到了同样的结果。 Unsigned chars {63, 240, 0, 0, 0, 0, 0, 0, 0}是双数的表示方法。1.

它的输出。3.03865e-319.

c++ type-conversion double unsigned-char
1个回答
1
投票

你把你的缓冲区绕错了。 应该是这样的

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

(在一个使用IEEE浮点的小二烯机器上).

现场演示

© www.soinside.com 2019 - 2024. All rights reserved.