Zac Taylor Zac Taylor - 2 months ago 16
C Question

Using 0b representation to print (printf) float

I'm trying to express a fractional number in binary and then have it print out as a float. I've done the fixed point to floating point conversion.

The number in decimal: -342.265625

fixed point: -101010110.010001

32-bit float: 11000011101010110010001000000000

64-bit float (double): 1100000001110101011001000100000000000000000000000000000000000000

*I've double checked with an IEEE 754 Converter

*I'm also aware that printf changes floats into doubles to print them, but declaring it as a double should work? I thought...?

Code:

int main()
{

float floaty = 0b11000011101010110010001000000000;
double doubley = 0b1100000001110101011001000100000000000000000000000000000000000000;
printf("Float: %f\n", floaty);
printf("Double: %lf\n", doubley);

}


Output:

Float: 3282772480.000000
Double: 13868100853597995008.000000


The compiler is gcc and the standard is c99

Answer

You can use the binary constants with some more work.

We will have to assume the floating point represented using IEEE 754, and the system is in little endian:

uint32_t value = 0b11000011101010110010001000000000;
float f;
memcpy( &f , &value , sizeof( f ) );
printf( "%f\n" , f );