从内存中提取 double 的字节值
我正在尝试从计算机内存中提取双精度的字节值。这样做的原因是准确性,因为向用户表示的最终值执行了一些舍入。
理想情况下,我希望能够从数字中提取符号、指数和尾数(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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你做对了。您现在可以将
p
视为数组unsigned char[sizeof(double)]
。例如:
对于
d = 0.125
,将打印00 00 00 00 00 00 C0 3F
。反转字节顺序并分解为:指数字段的值为 1020,经过 1023 的偏差校正后给出的指数为 -3,尾数为 1.0,包含隐式前导 1 后,值为 2 −3=1/8。
You're doing it right. You can treat
p
as an arrayunsigned char[sizeof(double)]
now.For example:
For
d = 0.125
this prints00 00 00 00 00 00 C0 3F
. Reversing endianness and decomposing into parts, this is: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.
如果您的动机只是准确性,请使用 printf("%a\n", d);
它显示的信息与二进制表示形式相同,但它以几乎人类的格式显示-可读。此处(即,对于
d=2;
),它显示0x1p+1
。0x
后面的数字是尾数,在 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 displays0x1p+1
. The number after0x
is the mantissa, normalized between 1 and 2, and in hexadecimal. The number afterp
is the exponent. It is displayed in decimal but it represents a power of two.