This question already has an answer here:
这个问题在这里已有答案:
- How to convert a byte array into double in C? 3 answers
如何在C中将字节数组转换为double? 3个答案
I read from a socket some hex data. The specification for this protocol tells me that the following 8 bytes represent a double Value.
我从套接字读取一些十六进制数据。该协议的规范告诉我,以下8个字节代表双值。
So I have for example 8 byte like:
所以我有例如8字节:
0x3F 0xD1 0x9B 0x94 0xC0 0x00 0x00 0x00
(This value is saved in a char array so Array[0] = 0x3F
, `Array[1] = 0xD1è...)
(此值保存在char数组中,因此Array [0] = 0x3F,`Array [1] =0xD1è...)
The represented double value is: 0.275120913982
代表的双重值是:0.275120913982
How can I convert these 8 bytes to this double value?
如何将这8个字节转换为此double值?
I tried a lot of different things, but nothing works really. So I have no idea how I can manipulate it to a double.
我尝试了很多不同的东西,但没有任何作用。所以我不知道如何将它操纵为双倍。
1 个解决方案
#1
You can use union, this works for me:
你可以使用union,这对我有用:
#include <iostream>
using namespace std;
int main() {
union { char b[8]; double d; };
b[7] = 0x3F;
b[6] = 0xD1;
b[5] = 0x9B;
b[4] = 0x94;
b[3] = 0xC0;
b[2] = 0x00;
b[1] = 0x00;
b[0] = 0x00;
cout << "Double: " << d << endl;
return 0;
}
Please note reverse order of bytes. It depends on endianness and can differ on your machine. Anyway it outputs:
请注意字节的反向顺序。它取决于字节顺序,并且可能在您的计算机上有所不同。无论如何它输出:
Double: 0.275121
#1
You can use union, this works for me:
你可以使用union,这对我有用:
#include <iostream>
using namespace std;
int main() {
union { char b[8]; double d; };
b[7] = 0x3F;
b[6] = 0xD1;
b[5] = 0x9B;
b[4] = 0x94;
b[3] = 0xC0;
b[2] = 0x00;
b[1] = 0x00;
b[0] = 0x00;
cout << "Double: " << d << endl;
return 0;
}
Please note reverse order of bytes. It depends on endianness and can differ on your machine. Anyway it outputs:
请注意字节的反向顺序。它取决于字节顺序,并且可能在您的计算机上有所不同。无论如何它输出:
Double: 0.275121