#include #include /** * floatbits - fun printing the bits of a number. */ /** * Procedure: * show_int_bits * Parameters: * i, an integer * Purpose: * Show all the bits in i * Produces: * [Nothing, called for the side effect.] * Preconditions: * [No additional] * Postconditions: * 32 bits (character 0 or character 1) appear on output. */ void show_int_bits (int i) { int j; int current; // For each bit position for (j = 31; j >= 0; j--) { // Check what the bit at position j is // Need the number corresponding to 00000100000000000, that is, // 1 followed by j 0's // Can do it with expontentiation, but that's wasteful current = 0x1 << j; if ((i & current) == 0) printf ("0"); else printf ("1"); } } // show_int_bits /** * Interpret a float as an int. Note that this is *not* the same as * coercing the float to an int, which effectively rounds the float. * Instead, we indicate that we want the same set of bits interpreted * in another way. */ int f2i (float f) { return *((int *) &f); } // f2i /** * main */ int main (int argc, char *argv[]) { // Grab element 1 of argv as a float, but interpret the bits as an // integer. float f = atof (argv[1]); printf ("%f is ", f); show_int_bits (f2i (f)); printf ("\n"); return EXIT_SUCCESS; } // main