2.93 Float Absval

★★

Problem:

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

/* Compute |f|. If f is NaN, then return f." */
float_bits float_absval(float_bits f);

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

#include <stdio.h>
#include <assert.h>

typedef unsigned float_bits;

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

    int is_nan = (exp == 0xFF) && (frac != 0);
    if (is_nan) {
        return f;
    }
    return (0 << 31) | exp << 23 | frac;
}

int main() {
    assert(float_absval(0x89)==0x89);
    assert(float_absval(0x89999999)==0x9999999);
    assert(float_absval(0x7F900000)==0x7F900000);
    return 0;
}

Last updated