How does "% f" work in C?

Hey, I need to know how% f works, here's how

printf("%f",number);

extracting a floating point number from a series of bits in a quantity. Consider the code:

 main()
{
int i=1;
printf("\nd  %d\nf %f",i,i);
}

Output:

d 1

f -0.000000

Thus, ultimately, it does not depend on the variable "i", but depends on the use of% d and% f (or any other). I just need to know how% f extracts a floating-point number corresponding to the series of bits in the 'i'

For all those who misunderstood my question, I know that% f cannot be used for an integer and will load garbage values ​​if the size of the integer is less than the float. As for my case, the size of integer and float is 4 bytes.

Let me be clear, if the value is 1, then the corresponding binary value i will be as follows:

0000 0000 0000 0000 0000 0000 0000 0001 [32 bits]

% f extract -0.0000, . ( , .., IEEE 754)

[, , ]

+4
4

undefined "%f" int, : , .

, "%f", i, (, printf() scanf()) .

+3

, "%" - undefined, , C, .

:

printf , , , , . printf , , ​​, printf , ( ) 64 . int, 32 , printf 32 int 32 , . , , , -0.0.

+2

.

, , ?

- fixed point: n, m - , - . . , , 0 1.

floating point. IEEE 754 spec , . , , .

.

0

(float x;) , " " .

, x < 0. , - . , .

. , , .. int integer = x;. , base-10 log10(). . log10(0) - undefined, . 0 , , 10 ^ digit_index, 10- ().

for (i=digits; i>=0; i--)
    dig = (integer / pow(10,i)) % 10;

..

( , ) . , 10 ^ frac_digits. , ( ).

C , .

IEEE . , 3,57 × 10 2 357.0. -. "" , 1 . , , .

, , " ". - . .


float printf , . , , , . , float double. , ( hex ), 2 64- :

double f,             double f
0xabcdefgh 0xijklmnop 0xabcdefgh 0xijklmnop

printf int, double. , 32- int, printf, , , printf, . .

To get an integer representation, you will need to use piracy with a pointer.

printf("%d %f\n", *(int *)&f, f);

What reads (from right to left): take the address of the float, treat it as a pointer-to-int, follow the pointer.

0
source

Source: https://habr.com/ru/post/1535142/


All Articles