2.94 Float Twice

★★★

Problem:

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

/* Compute 2*f. If f is NaN, then return f. */
float_bits float_twice(float_bits f);

For floating-point number f, this function computes 2.0 * 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:

typedef unsigned float_bits;

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

    int is_nan_oo = (exp == 0xFF);
    if (is_nan_oo) {
        return f;
    }
    if (exp == 0xFF-1) {
        frac = 0;
    } else if (exp == 0) {
        /* Denormalized */
        frac <<= 1;    
    } else {
        /* Normalized */
        exp += 1;
    }
    return sign << 31 | exp << 23 | frac;
}

Last updated