且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将8个字节转换为两倍

更新时间:2023-02-04 12:42:36

您说的是 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 。为此,可以在一个 double 是IEEE754 binary64的小端机上进行移植:

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).