• 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.

    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上是小端,把字节顺序颠倒过来。

    1. /* @ref: https://www.geeksforgeeks.org/c-float-and-double/ */
    2. #include
    3. #ifndef u_int8_t
    4. typedef unsigned char u_int8_t;
    5. #endif
    6. #ifndef u_int32_t
    7. typedef unsigned int u_int32_t;
    8. #endif
    9. typedef union {
    10. u_int8_t a[4];
    11. float f;
    12. u_int32_t i;
    13. } float_t;
    14. int main(int argc, char *argv[])
    15. {
    16. float_t x;
    17. x.a[0] = 0x00, x.a[1] = 0x40; x.a[2] = 0x82; x.a[3] = 0x42;
    18. printf("%f\n", x.f);
    19. return 0;
    20. }

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

  • 相关阅读:
    leetcode中级2,Sorting and Searching:347. 前 K 个高频元素
    浮动元素的特点(2)
    字节面试遇到的一个超级复杂的输出题,前端人必看系列,搞定之后再也没有输出题可以难倒你
    适用于遥感图像处理的神经网络
    python中arrow库用法详解
    【Spring中的设计模式】
    RDD—Transformation算子
    django rest framework框架中用到的组件
    使用OpenCV计算两幅图像的协方差
    暗恋云匹配匿名交友聊天系统开发
  • 原文地址:https://blog.csdn.net/fareast_mzh/article/details/132819162