For example the given program
FILE *f = fopen("test.txt","w");
double d = 5.2;
fwrite(&d, sizeof(typeof(d)), 1, f);
fclose(f);
when U use xxd
to view the content I get
//binary
0000000: 11001101 11001100 11001100 11001100 11001100 11001100 ......
0000006: 00010100 01000000 .@
//hex
0000000: cdcc cccc cccc 1440 .......@
but I found How to represent FLOAT number in memory in C that it should look like
0 10000001 01001100110011001100110
so I am not sure if its the same binary in memory and file or I am completely wrong. How can i determine the float value from given example?
The bit pattern you show, 0 10000001 01001100110011001100110
, is for an IEEE-754 basic 32-bit binary floating-point representation, often used for float
. You request the representation of a double
, which often uses IEEE-754 basic 64-bit binary.
The bytes you show, cdcc cccc cccc 1440
, are a representation of approximately 5.2, in a little-endian order. In the high-value byte, the first bit, in position 0x80
, is zero. It is the sign bit, and zero means positive. The next seven bits, 0x40
, and the four bytes from the next byte, the 1
of 0x14
, are the exponent. Together, they are 0x401
. The exponent is biased by 0x3ff
. So, with an exponent encoded as 0x401
, the actual exponent is 2, meaning 22.
The remaining bits encode the trailing bits of the significand. They are 0x4cccccccccccd
. For normal numbers, the significand is put after a “radix point” (the general equivalent of a decimal point) with 1 before the point: 1.4cccccccccccd16. In decimal, that is approximately 1.3 (exactly 1.3000000000000000444089209850062616169452667236328125).
Together, the value is + 22 • 1.3000000000000000444089209850062616169452667236328125 = 5.20000000000000017763568394002504646778106689453125.