从内存中提取 double 的字节值

发布于 2024-12-26 00:48:12 字数 326 浏览 3 评论 0原文

我正在尝试从计算机内存中提取双精度的字节值。这样做的原因是准确性,因为向用户表示的最终值执行了一些舍入。

理想情况下,我希望能够从数字中提取符号、指数和尾数(IEEE 754 标准)

据我所知,转换为 unsigned char 是正确的方法。我有以下代码片段(在其他地方被盗),但我不相信结果 - 任何整数值都没有字节输出:

double d = 2;
unsigned char *p = (unsigned char*)&d;

任何人都可以指导我正确的方向,以便准确提取双数的字节表示,或者给出关于如何进行的任何建议/意见?

I'm trying to extract the byte value of a double from the computer's memory. The reason for this is accuracy, as the final value that is represented to the user has some rounding performed.

Ideally, I want to be able to extract the sign, exponent and mantissa from the number (IEEE 754 standard)

From what I understand, casting to an unsigned char is the way to go. I have the following code snippet (stolen elsewhere), but I don't trust the results - there's no byte output for any integer values:

double d = 2;
unsigned char *p = (unsigned char*)&d;

Can anyone guide me in the right direction in order to extract byte representation of double numbers accurately, or give any advice/comments on how to proceed?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

逆光飞翔i 2025-01-02 00:48:12

你做对了。您现在可以将 p 视为数组 unsigned char[sizeof(double)]

例如:

for (int i = 0; i != sizeof(double); ++i)  printf("%02X ", p[i]);

对于d = 0.125,将打印00 00 00 00 00 00 C0 3F。反转字节顺序并分解为:

00111111 11000000 0 0 0 0 0 0
   3F       C0    0 0 0 0 0 0

0   01111111100   0...<52 times>...0
S     Exponent         Mantissa
+     1023 - 3           1.0

指数字段的值为 1020,经过 1023 的偏差校正后给出的指数为 -3,尾数为 1.0,包含隐式前导 1 后,值为 2 −3=1/8。

You're doing it right. You can treat p as an array unsigned char[sizeof(double)] now.

For example:

for (int i = 0; i != sizeof(double); ++i)  printf("%02X ", p[i]);

For d = 0.125 this prints 00 00 00 00 00 00 C0 3F. Reversing endianness and decomposing into parts, this is:

00111111 11000000 0 0 0 0 0 0
   3F       C0    0 0 0 0 0 0

0   01111111100   0...<52 times>...0
S     Exponent         Mantissa
+     1023 - 3           1.0

The exponent field's value is 1020, which gives an exponent of −3 after correcting by the bias of 1023, and the mantissa is 1.0, after including the implicit leading 1. So the value is 2−3 = 1/8.

苍风燃霜 2025-01-02 00:48:12

如果您的动机只是准确性,请使用 printf("%a\n", d);

它显示的信息与二进制表示形式相同,但它以几乎人类的格式显示-可读。此处(即,对于d=2;),它显示0x1p+10x 后面的数字是尾数,在 1 和 2 之间标准化,采用十六进制。 p 后面的数字是指数。它以十进制显示,但代表 2 的幂。

If your motivation is only accuracy, use printf("%a\n", d);

It displays the same information as going to the binary representation would, but it displays it in a format that's almost human-readable. Here (that is, for d=2;), it displays 0x1p+1. The number after 0x is the mantissa, normalized between 1 and 2, and in hexadecimal. The number after p is the exponent. It is displayed in decimal but it represents a power of two.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文