#include #include /// Print the bits of an int (spaces between each nibble and byte). /// /// Including this just for reference, so you can see how I modified /// it to make print_binary_f. void print_binary(int x) { for (int i=31; i >= 0; i--) { printf("%d", (x >> i) & 0x1); if (i % 8 == 0) printf(" "); if (i % 4 == 0) printf(" "); } printf("\n"); } /// Print the bits of the float by shifting and masking /// (in order from most significant, so shifted the most, /// to least significant), with spaces to distinguish /// sign, exp, and frac components. void print_binary_f(float x) { unsigned u = *(unsigned*)&x; for (int i=31; i >= 0; i--) { printf("%d", (u >> i) & 0x1); if (i == 32-1) printf(" "); if (i == 32-9) printf(" "); } } /// Print float in 3 different ways: /// - in decimal (%g) /// - hexadecimal (must force printf to think it's an int first) /// - binary void print_float(float x) { printf("%gf: 0x%08x (", x, *(int*)&x); print_binary_f(x); printf(")\n"); } /// Try running this to see the representations of different /// float values in binary, and some instances showing that /// floats don't always abide by the rules of math! int main(int argc, char const *argv[]) { printf("# Integer representation\n"); printf("%d (int) in binary:\n", 1); print_binary(1); printf("\n# Float representation\n"); print_float(-0.0f); print_float(1.0f); //1.0 * 2^0 -> E=0, exp=0+127 print_float(INFINITY); print_float(-NAN); printf("\n# Exploring math\n"); printf("%g\n", 3.14+1e100 - 1e100); printf("%g\n", 3.14 + (1e100 - 1e100)); printf("Not associative!\n"); printf("%.20g\n", 100 * (0.1 + 0.2) ); printf("%.20g\n", (100 * 0.1) + (100 * 0.2) ); printf("Not distributive!\n"); return 0; } ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// //> # Integer representation //> 1 (int) in binary: //> 0000 0000 0000 0000 0000 0000 0000 0001 //> //> # Float representation //> -0f: 0x80000000 (1 00000000 00000000000000000000000) //> 1f: 0x3f800000 (0 01111111 00000000000000000000000) //> inff: 0x7f800000 (0 11111111 00000000000000000000000) //> nanf: 0xffc00000 (1 11111111 10000000000000000000000) //> //> # Exploring math //> 0 //> 3.14 //> Not associative! //> 30.000000000000003553 //> 30 //> Not distributive! /////////////////////////////////////////////////////////////