/* =============================================================================
 * 07_float_fields.c  --  (supplement) the three fields of an IEEE 754 float
 * =============================================================================
 *
 * [Questions this demo answers]
 *   - A 32-bit float is "sign, exponent, fraction". Which bits are which, and
 *     how do they combine into a value?
 *   - What are normalized, denormalized and special (inf, NaN) values?
 *   - Why is 0.1 not exact, and why does 16777217 not fit in a float?
 *
 * [How to build & run]
 *   make 07_float_fields && ./07_float_fields
 *
 * [How to read the output]
 *   One row per value: its bits split as  s | eeeeeeee | fffffff...,  the
 *   class, and the value rebuilt by hand from the formula. The rebuilt value
 *   must equal the float itself; the last column checks that.
 *
 * [Systems link / CS:APP 2.4]
 *   The Fall 2026 lectures skip floating point (CS:APP 2.4), but Lecture 1's
 *   Reality #1 and the float puzzles traditionally in datalab rely on it.
 *   This demo is the minimum you need: how the 32 bits are laid out and decoded.
 *     normalized   (exp != 0 and != 255): value = (-1)^s * 1.f * 2^(exp-127)
 *     denormalized (exp == 0)           : value = (-1)^s * 0.f * 2^(1-127)
 *     special      (exp == 255)         : f == 0 -> +/-infinity, else NaN
 * -------------------------------------------------------------------------- */

#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <math.h>        /* ldexp: x * 2^k computed exactly; INFINITY, NAN    */
#include "bits.h"

/* ---------------------------------------------------------------------------
 * decode  --  print the fields of f and rebuild its value from them.
 *
 * [Idea]
 *   Copy the 4 bytes of the float into a uint32_t (memcpy is the portable way
 *   to reinterpret bits), split off the fields with shifts and masks, then
 *   apply the formula for the field's class.
 * [Parameters] label -- text to print; f -- the float.
 * [Returns] nothing.
 * [Edge cases] NaN never equals itself, so the "rebuilt == f" check for NaN
 *   compares with isnan instead.
 * ------------------------------------------------------------------------- */
static void decode(const char *label, float f) {
    uint32_t u;
    memcpy(&u, &f, sizeof u);
    uint32_t s = u >> 31;                   /* 1 bit                          */
    uint32_t e = (u >> 23) & 0xff;          /* 8 bits                         */
    uint32_t frac = u & 0x7fffff;           /* 23 bits                        */

    const char *cls;
    double rebuilt;
    if (e == 0xff) {
        cls = frac == 0 ? "infinity" : "NaN";
        rebuilt = frac == 0 ? (s ? -INFINITY : INFINITY) : NAN;
    } else if (e == 0) {
        cls = "denormalized";
        rebuilt = ldexp((double)frac / (1 << 23), 1 - 127);       /* 0.f * 2^-126 */
        if (s) rebuilt = -rebuilt;
    } else {
        cls = "normalized";
        rebuilt = ldexp(1.0 + (double)frac / (1 << 23), (int)e - 127); /* 1.f * 2^E */
        if (s) rebuilt = -rebuilt;
    }
    int ok = isnan(f) ? isnan(rebuilt) : (rebuilt == (double)f);
    printf("  %-12s %u | %s | %s  %-12s E=%4d  rebuilt=%-14.9g %s\n",
           label, s, bin(e, 8), bin(frac, 23), cls,
           e == 0 ? 1 - 127 : (int)e - 127, rebuilt, ok ? "ok" : "MISMATCH");
}

int main(void) {
    printf("=== Demo 07 (supplement): IEEE 754 single-precision fields ===\n");
    printf("  value        s | exponent  | fraction (23 bits)\n");
    decode("1.0", 1.0f);
    decode("-2.5", -2.5f);
    decode("15213.0", 15213.0f);
    decode("0.1", 0.1f);
    decode("FLT_MIN", 1.17549435e-38f);          /* smallest normalized       */
    decode("1.4e-45", 1.40129846e-45f);          /* smallest denormalized     */
    decode("-0.0", -0.0f);
    decode("+inf", INFINITY);
    decode("NaN", NAN);

    printf("\n  0.1f is really %.20f (0.1 has no finite binary expansion)\n", 0.1f);
    float big = 16777216.0f;                     /* 2^24                      */
    float next = big + 1.0f;                     /* 2^24 + 1 needs 25 bits    */
    printf("  16777216.0f + 1.0f = %.1f  (a float holds 24 significant bits)\n\n", next);

    printf("Observations:\n");
    printf("  * A float is three unsigned fields: 1 sign bit, 8 exponent bits with a\n");
    printf("    bias of 127, and 23 fraction bits with an implied leading 1.\n");
    printf("  * exponent 0 = denormalized (no implied 1, gradual underflow to 0);\n");
    printf("    exponent 255 = infinity (fraction 0) or NaN (fraction != 0).\n");
    printf("  * The fraction field explains rounding: 24 significant bits, so 2^24 + 1\n");
    printf("    is not representable and 0.1 is stored approximately.\n");
    return 0;
}
