Cod*_*tor 1 c floating-point printf
I am trying to print out the floating point values 0x40a00000 and 0xc0200000. But the values that I print out and the correct values according to the IEEE-754 Floating Point Converter (https://www.h-schmidt.net/FloatConverter/IEEE754.html) are completely different:
The values I should get according to the IEEE converter:
0x3F800000 = 5.00
0xBF000000 = -2.50
Run Code Online (Sandbox Code Playgroud)
The values I get when running:
float tmp1 = 0x40a00000;
float tmp2 = 0xc0200000;
printf("tmp1 = %.2f\n", tmp1);
printf("tmp2 = %.2f\n", tmp2);
Run Code Online (Sandbox Code Playgroud)
is
tmp1 = 1084227584.00
tmp2 = 3223322624.00
Run Code Online (Sandbox Code Playgroud)
For some reason my C code isn't formatting the bits of the floating point values according to IEEE standards and is instead formatting them as if it were an int with a decimal point
These are assigning the float representation of the hexadecimal numbers to the floats.
Instead, do this:
int i1 = 0x40a00000;
int i2 = 0xc0200000;
float tmp1, tmp2;
memcpy(&tmp1, &i1, sizeof(int));
memcpy(&tmp2, &i2, sizeof(int));
Run Code Online (Sandbox Code Playgroud)
Print them:
printf("tmp1 = %.2f\n", tmp1);
printf("tmp2 = %.2f\n", tmp2);
Run Code Online (Sandbox Code Playgroud)
Output:
tmp1 = 5.00
tmp2 = -2.50
Full example:
#include <stdio.h>
#include <string.h>
int main(void)
{
int i1 = 0x40a00000;
int i2 = 0xc0200000;
float tmp1, tmp2;
memcpy(&tmp1, &i1, sizeof(int));
memcpy(&tmp2, &i2, sizeof(int));
printf("tmp1 = %.2f\n", tmp1);
printf("tmp2 = %.2f\n", tmp2);
}
Run Code Online (Sandbox Code Playgroud)