> For the complete documentation index, see [llms.txt](https://valineliu.gitbook.io/deuterium-wiki/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://valineliu.gitbook.io/deuterium-wiki/reading/cs-jing-dian-shu-ji/csapp-3e-homework-solution/2.-representing-and-manipulating-information/2.95-float-half.md).

# 2.95 Float Half

★★★

**Problem**:

Following the bit-level floating-point coding rules, implement the function with the following prototype:

```c
/* Compute 0.5*f. If f is NaN, then return f. */
float_bits float_half(float_bits f);
```

For floating-point number f, this function computes 0.5 \* f. If f is NaN, your function should simply return f.

Test your function by evaluating it for all 2^32 values of argument f and comparing the result to what would be obtained using your machine's floating-point operations.

Code:

```c
typedef unsigned float_bits;

float_bits float_half(float_bits f) {
    unsigned sign = f >> 31;
    unsigned exp = f >> 23 & 0xFF;
    unsigned frac = f & 0x7FFFFF;
    unsigned rest = f & 0x7FFFFFFF;

    /* Round to even. */
    int addition = (frac & 0x3) == 0x3;

    if (exp == 0) {
        /* Denormalized */
        frac >>= 1;
        frac += addition;
    } else if (exp == 1) {
        /* Normalized to denormalized */
        exp = 0;
        rest >>= 1;
        rest += addition;
        frac = rest & 0x7FFFFF;
    } else {
        exp -= 1;
    }

    return sign << 31 | exp << 23 | frac;
}
```

###
