如何在 C 中表示内存中的 FLOAT 数 [英] How to represent FLOAT number in memory in C

查看:11
本文介绍了如何在 C 中表示内存中的 FLOAT 数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在阅读教程时,我遇到了如何在内存中表示浮点数.本教程有一个带有浮点数的示例.

While reading a tutorial I came across how to represent Float number in memory. The tutorial had an example with a floating point number.

   float a=5.2  with below Diagram

谁能告诉上图中这个 5.2 是如何转换成二进制的,以及它是如何在内存中表示的?

Can anyone please tell how this 5.2 is converted in to binary and how it is represented in memory in above the above diagram?

推荐答案

如前所述,5.2 表示为符号位、指数和尾数.你如何编码 5.2?

As was said, 5.2 is represented as a sign bit, an exponent and a mantissa. How do you encode 5.2?

5 很简单:

101. 

其余的,0.2 是 1/5,所以将 1.00000...(十六进制)除以 5,得到 0.3333333...(十六进制).

The rest, 0.2 is 1/5, so divide 1.00000... (hex) by 5 and you get 0.3333333... (hex).

(如果你考虑少一点,这可以更容易地遵循:0.FFFF...F/5 = 3,所以它很容易看出 0.FFFF.../5 = 0.33333....除以 5 时,丢失的一位无关紧要,所以 1.0000.../5 =0.3333... 也是).

(This can be followed more easily if you consider one bit less: 0.FFFF...F / 5 = 3, so it is easy to see that 0.FFFF... / 5 = 0.33333.... That one missing bit doesn't matter when dividing by 5, so 1.0000... / 5 = 0.3333... too).

那应该给你

0.0011001100110011001100110011... 

加5,得到

101.00110011001100110011...         exp 0    (== 5.2 * 2^0)

现在右移(标准化,即确保最高位刚好在小数点之前)并相应地调整指数:

Now shift it right (normalize it, i.e. make sure the top bit is just before the decimal point) and adjust the exponent accordingly:

1.010011001100110011001100110011... exp +2   (== 1.3 * 2^2 == 5.2)

现在您只需将 127 的偏差(即 129 = 0b10000001)添加到指数并存储:

Now you only have to add the bias of 127 (i.e. 129 = 0b10000001) to the exponent and store it:

0 10000001 1010 0110 0110 0110 0110 0110 

忘记尾数的前1位(它总是应该是1,除了一些特殊值,所以不存储),你得到:

Forget the top 1 of the mantissa (which is always supposed to be 1, except for some special values, so it is not stored), and you get:

01000000 10100110 01100110 01100110

现在您只需决定小端或大端.

Now you only have to decide little or big endian.

这并不是它的工作原理,但它或多或少是在将 5.2 这样的数字转换为二进制时发生的情况.

This is not exactly how it works, but that is more or less what happens when a number like 5.2 is converted to binary.

这篇关于如何在 C 中表示内存中的 FLOAT 数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆