C float Memory Representation

How float and double are stored?

C language follows the IEEE 754 standard for representing floating point values in the memory. Unlike the int type that is directly stored in the memory in binary form, the float values are divided into two parts: exponent and mantissa, and then stored.

According to IEEE 754, the floating point values consist of 3 components:

  1. Sign Bit: This represents the sign of the number. 0 represents positive while 1 represents negative.
  2. Biased Exponent: The exponent of the number cannot be directly stored as it can be both negative or positive, so we use a biased exponent where we add some bias to the exponent.
  3. Normalized Mantissa: Matissa is the number in scientific notation, i.e. precision bits of the number.

C float Memory Representation

The size of the float is 32-bit, out of which:

  • The most significant bit (MSB) is used to store the sign of the number.
  • The next 8 bits are used to store the exponent.
  • The remaining 23 bits are used to store the mantissa.

C float Memory Representation_第1张图片

Example

Let’s take 65.125 as a decimal number that we want to store in the memory.

Converting to Binary form, we get:
65     = 1000001
0.125  = 001
So, 
65.125 = 1000001.001  # 从左边找到第0个不是0的数,小数点移动到这个数的右边
       = 1.000001001 x 2e6
# 去掉最前面的1.  从小数点往后数最多23位
Normalized Mantissa = 000001001

Now, according to the standard,     # 要加上0x7f
we will get the baised exponent by adding the exponent to 127,
       = 127 + 6 = 133
Baised exponent = 10000101

And the signed bit is 0 (positive)

So, the IEEE 754 representation of 65.125 is,
0 10000101 00000100100000000000000

用union验证一下,注意字节序。

每4位分组

0100 0010, 1000 0010, 0100 0000, 0000 0000

4       2         8       2        4      0        0       0

Linux上是小端,把字节顺序颠倒过来。

/* @ref: https://www.geeksforgeeks.org/c-float-and-double/ */
#include 

#ifndef u_int8_t
typedef unsigned char u_int8_t;
#endif
#ifndef u_int32_t
typedef unsigned int u_int32_t;
#endif

typedef union {
    u_int8_t a[4];
    float f;
    u_int32_t i;
} float_t;

int main(int argc, char *argv[])
{
        float_t x;
        x.a[0] = 0x00, x.a[1] = 0x40; x.a[2] = 0x82; x.a[3] = 0x42;
        printf("%f\n", x.f);

        return 0;
}

 mzh@DESKTOP-GITL67P:~$ cc -g float.c
mzh@DESKTOP-GITL67P:~$ ./a.out
65.125000

你可能感兴趣的:(c语言,开发语言)