/* 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! Jeff Ondich Last updated 14 Oct 2016 */ #include int main() { float x, y, z; x = -6.375; float *addressOfX = &x; unsigned int *addressOfXInterpretedAsInteger = (unsigned int *)addressOfX; unsigned int xInterpretedAsInteger = *addressOfXInterpretedAsInteger; printf("%.3f : 0x%08x\n", x, xInterpretedAsInteger); x = -0.0; printf("%.3f : 0x%08x\n", x, *((unsigned int *)(&x))); x = -32.0; y = 11.0; z = y / x; printf("%.3f : 0x%08x\n", z, *((unsigned int *)(&z))); // Repeating binary... x = 3.0; y = 1.0; z = y / x; printf("%.3f : 0x%08x\n", z, *((unsigned int *)(&z))); // Infinity x = 0.0; y = 1.0; z = y / x; printf("%.3f : 0x%08x\n", z, *((unsigned int *)(&z))); // Not a number! x = 0.0; y = 0.0; z = y / x; printf("%.3f : 0x%08x\n", z, *((unsigned int *)(&z))); // Mess with z and a big number printf("Begin David's weird idea\n"); x = 0.0; y = 1.0; z = y / x; // z is now +inf unsigned int bigNumber = 0x7f7fffff; x = *((float *)&bigNumber); printf("%.3f : 0x%08x\n", x, bigNumber); y = z / x; printf("%.3f : 0x%08x\n", y, *((unsigned int *)(&y))); y = x / z; printf("%.3f : 0x%08x\n", y, *((unsigned int *)(&y))); printf("Done with David's weird idea\n"); return 0; }