简体   繁体   English

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

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

I am trying to convert an unsigned char buffer array into a double.我正在尝试将unsigned char缓冲区数组转换为双精度。 Why does this not copy the bytes into the double as they are in the array?为什么这不会将字节复制到数组中的双精度数中?

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

I also tried doing this:我也试过这样做:

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

I looked at this post here , but it only got the same results.我在这里查看了这篇文章,但它只得到了相同的结果。 The unsigned chars {63, 240, 0, 0, 0, 0, 0, 0} is the representation of the double number 1 .无符号字符 {63, 240, 0, 0, 0, 0, 0, 0} 是双精度数1的表示。

It outputs: 3.03865e-319 .它输出: 3.03865e-319

You've got your buffer round the wrong way.您的缓冲区以错误的方式进行。 It should be:它应该是:

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

(on a little-endian machine using IEEE floating point). (在使用 IEEE 浮点的小端机器上)。

Live demo现场演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 C ++:如何将十六进制字符转换为无符号字符? - C++: how do I convert hex char to unsigned char? 如何将char *缓冲区转换为unsigned short int * bufferSh - c++ - How to convert char * buffer to unsigned short int * bufferSh 如何在插件中将Java缓冲区(即,无符号字符*)从C ++返回到NodeJS? - How do I return a Javascript Buffer (i.e an unsigned char *) from C++ to NodeJS in an addon? C ++:如何将无符号字符转换为表示该字符具有的二进制值的字符串? - C++: how do I convert an unsigned char to a string representing the binary value that the char has? 如何将char *缓冲区转换为unsigned char缓冲区 - How can I convert char* buffer to unsigned char buffer 如何在 C/C++ 中将 unsigned char* 转换为 unsigned char 数组? - How to convert unsigned char* to an unsigned char array in C/C++? unsigned char *在C ++中加倍 - unsigned char* to double in c++ 如何在C ++中将char *转换为unsigned short - How to convert char* to unsigned short in C++ 如何使用boost.python将预先填充的“unsigned char *”缓冲区传递给C ++方法? - How do I pass a pre-populated “unsigned char*” buffer to a C++ method using boost.python? 如何将双精度型转换为无符号字符? - How to convert a double into an unsigned char?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM