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:
The size of the float is 32-bit, out of which:
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