/* floatingpoint.c Jeff Ondich Last updated 22 April 2019 Fooling around with floating point numbers. This code uses some tricks with addresses and type-casting to help you see the internal structure of float variables. This code assumes that your C compiler treats float variables as IEEE 754 32-bit floating point numbers, and that unsigned int variables are 32-bit variables. At a terminal with the gcc compiler installed, you can compile this program like so: gcc -o floatingpoint floatingpoint.c and then just run it with: ./floatingpoint Have fun! */ #include unsigned int floatAsUnsignedInt(float x); void printFloatAsInt(float x); float intAsFloat(unsigned int n); void printIntAsFloat(unsigned int n); int main() { float x, y, z; x = -12.5; printFloatAsInt(x); unsigned int k = floatAsUnsignedInt(x); printIntAsFloat(k); x = -0.0; printFloatAsInt(x); x = -16.0; y = 5.0; z = y / x; printFloatAsInt(x); // Repeating binary... x = 6.0; y = 23.0; z = y / x; printFloatAsInt(x); // Infinity x = 0.0; y = 1.0; z = y / x; printFloatAsInt(x); // Not a number! x = 0.0; y = 0.0; z = x / y; printFloatAsInt(z); return 0; } // Utility functions unsigned int floatAsUnsignedInt(float x) { float *addressOfX = &x; unsigned int *addressOfXInterpretedAsInteger = (unsigned int *)addressOfX; unsigned int xInterpretedAsInteger = *addressOfXInterpretedAsInteger; return xInterpretedAsInteger; } void printFloatAsInt(float x) { printf("%.3f : 0x%08x\n", x, floatAsUnsignedInt(x)); } float intAsFloat(unsigned int n) { unsigned int *addressOfN = &n; float *addressOfNInterpretedAsFloat = (float *)addressOfN; float nInterpretedAsFloat = *addressOfNInterpretedAsFloat; return nInterpretedAsFloat; } void printIntAsFloat(unsigned int n) { printf("0x%08x : %.3f\n", n, intAsFloat(n)); }