设置浮点数地址处的值

huangapple go评论77阅读模式
英文:

gdb set value at address of a float

问题

I am learning about floating point number representation and I have the following C++ code:

#include <float.h>
int main()
{
    unsigned int a = 8;
    float f = 1;
    float fmax = FLT_MAX;

    float n = 3.402823669e+38;

    return 0;
}

When I print the value of f as binary in gdb like x/tw &f I get:
0 01111111 00000000000000000000000 (1 sign bit, 8 exp bits, 23 mantissa bits).
In hexadecimal it is 0x3f800000.

Now I want to see which number I will get if I make the exponent as large as possible.

So I do set *(&f) = 0x7f800000.

However, instead of getting the expected
0 11111111 00000000000000000000000,

I get something completely arbitrary like
0 10011101 11111110000000000000000,
which is 0x4eff0000, which is not the value I set.

This happens also if the set result doesn't exceed FLT_MAX.

Changing unsigned int a in this way works fine.

What could be a possible explanation to this behavior?

英文:

I am learning about floating point number representation and I have the following C++ code:

#include &lt;float.h&gt;
int main()
{
    unsigned int a = 8;
    float f = 1;
    float fmax = FLT_MAX;
    
    float n = 3.402823669e+38;

    return 0;
}

When I print the value of f as binary in gdb like x/tw &amp;f I get:
0 01111111 00000000000000000000000 (1 sign bit, 8 exp bits, 23 mantissa bits).
In hexadecimal it is 0x3f800000.

Now I want to see which number I will get if I make the exponent as large as possible.

So I do set *(&amp;f) = 0x7f800000.

However, instead of getting the expected
0 11111111 00000000000000000000000,

I get something completely arbitrary like
0 10011101 11111110000000000000000,
which is 0x4eff0000, which is not the value I set.

This happens also if the set result doesn't exceed FLT_MAX.

Changing unsigned int a in this way works fine.

What could be a possible explanation to this behavior?

答案1

得分: 1

这种行为的可能解释是什么?

OP将2139095040.0f的值赋给了f

*(&amp;f) = 0x7f800000就像*(&amp;f) = 2139095040.0f

2139095040.0f以16进制模式0x4eff0000编码为float

毫不奇怪。

英文:

> What could be a possible explanation to this behavior?

OP assigned the value of 2139095040.0f to f.


*(&amp;f) = 0x7f800000 is like *(&amp;f) = 2139095040.0f.

2139095040.0f is encoded in a float with hex pattern 0x4eff0000.

No surprise.

huangapple
  • 本文由 发表于 2023年5月11日 08:59:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/76223473.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定