将8个字节转换为两倍

编程入门 行业动态 更新时间:2024-10-24 20:22:45
本文介绍了将8个字节转换为两倍的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在将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 。为此,可以在一个 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).

更多推荐

将8个字节转换为两倍

本文发布于:2023-10-28 08:27:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1536093.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   两倍   字节

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!