将8个字节转换为两倍 [英] Converting 8 bytes to double
问题描述
我在将8字节转换为双精度字时遇到了一些问题。我有以下字节数组
I am facing some problem with converting 8 bytes to a double. I have following byte array
0x98 0xf9 0x38 0x4e 0x3a 0x9f 0x1c 0x43
我正在尝试按照
for (int i = 1; i < 8; i++)
mult[i] = 256 * mult[i - 1];
double out= buf[7] * mult[7] + buf[6] * mult[6] + buf[5] * mult[5] + buf[4] * mult[4] + buf[3] * mult[3] + buf[2] * mult[2] + buf[1] * mult[1] + buf[0] * mult[0];
但是它没有给出正确的答案。我出去等于4835915172658346392,实际值为2014093029293670。
But it is not giving the correct answer. I am getting out is equal to 4835915172658346392 and actual value is 2014093029293670.
注意: *(((double *)(buf))
可以正常工作,但我认为这不会对编译器和操作系统安全。
Note: *((double *) (buf))
works fine but I don't think it would be compiler and OS safe.
编辑:
long mult[8];
我从 mult [0] = 1
推荐答案
您说的是 0x98 0xf9 0x38 0x4e 0x3a 0x9f 0x1c 0x43
应该代表 2014093029293670
。
如果前者是该整数的 little-endian表示形式(采用IEEE754 binary64格式),则为true。因此,使用逐字节乘法(或等效地,移位)的方法将行不通,因为它们是算术运算。
This is true if the former is the little-endian representation of that integer in IEEE754 binary64 format. So your approach by using byte-by-byte multiplication (or equivalently, bit shifts) is not going to work, because those are arithmetic operations.
相反,您需要 alias 表示为 double
。为此,可以在一个
Instead you need to alias that representation as a double
. To do this portably, on a little-endian machine on which double
is IEEE754 binary64:
static_assert( sizeof(double) == 8 );
double out;
memcpy(&out, buf, sizeof out);
如果您希望此代码在端序不同的计算机上运行,则需要重新排列 buf
,然后再执行 memcpy
。 (这是假定该表示始终以小尾数格式获得,而您并未说明)。
If you want this code to work on a machine with different endianness then you will need to rearrange buf
before doing the memcpy
. (This is assuming that the representation is always obtained in little-endian format, which you didn't state).
这篇关于将8个字节转换为两倍的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!