• 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

  • 相关阅读:
    PowerShell 打开十六进制文件
    线性代数---第五章特征值和特征向量
    Go语言结构体
    ES / Kibana 快速安装配置记录
    Jetson Nano 部署(1):YOLOv5 目标检测实战介绍
    FPGA-结合协议时序实现UART收发器(一):UART协议、架构规划、框图
    糖尿病新世界杂志糖尿病新世界杂志社糖尿病新世界编辑部2022年第12期目录
    建造者模式 创建型模式之三
    经典同步问题
    SpringMVC入门
  • 原文地址:https://blog.csdn.net/fareast_mzh/article/details/132819162