2.92 Float Negate

★★

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_negate(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_negate(float_bits f) {
    unsigned sign = f >> 31;
    unsigned exp = f >> 23 & 0xFF;
    unsigned frac = f & 0x7FFFFF;

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

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

Last updated