深入理解浮点数存储

引言

在 c 程序开发时,经常会碰到数据转换的情况。 本文表述了对于浮点数如何存储的理解。

浮点数在内存存储示例

#include     <stdio.h>
#include <stdlib.h>

/**
* @brief The entry of this program
*
* @param argc counts of argument
* @param argv argument variables stored in
*
* @return EXIT_SUCCESS
*/

int main (int argc, char **argv)
{

float f = 7.5;
unsigned int i = *(unsigned int *)&f;
printf ("i:0x%x\n", i);
return EXIT_SUCCESS;
} //end of function main

输出结果

i:0x40F00000

解释

浮点数格式

|                                                               |
|<------------------------4Bytes/32Bits------------------------>|
|                                                               |
|1Bit(Sign:+/-)    23Bits(Digit)                                |
+-+---------------+---------------------------------------------+
|x|x x x x x x x x|x x x x x x x x x x x x x x x x x x x x x x x|
+-+---------------++-+-+----------------------------------------+
   8Bits(Exp)      | | +-(2^-3)
		   | +-(2^-2)
		   +-(2^-1)

浮点数7.5如何存储

+7.5 = 3.75 * (21) = 1.875 * (22)
Sign = 0
Exp - 127 = 2
Exp = 129 = 1000 0001(Binary)
0.875 = 0.5 + 0.25 + 0.125
= (2-1) + (2-2) + (2-3)
Digit = 111 0000 0000 0000 0000 0000(Binray)

将上述计算结果代如浮点数格式后,i即为0x40F00000

 1Bit(+/-)         23Bits(Digit)
+-+---------------+---------------------------------------------+
|0|1 0 0 0 0 0 0 1|1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0|
+-+---------------+---------------------------------------------+
   8Bits(Exp)

+---------------+---------------+---------------+---------------+
|0 1 0 0 0 0 0 0|1 1 1 1 0 0 0 0|0 0 0 0 0 0 0 0|0 0 0 0 0 0 0 0|
+---------------+---------------+---------------+---------------+
 0x40              0xF0            0x00            0x00