Silverfin
Silverfin

Reputation: 495

Doubling and dividing floating point values

I have the function which I believe will convert an int into a floating point value split into the sign exponent and fraction components of the value. Using IEEE 754 to represent Float values.

enter image description here

unsigned test(unsigned x) {    
    // split the given bits of sign exponent and fraction, combine to return

    unsigned int sign = (x & 0x80000000) >> 31;
    unsigned int expo = (x & 0x7F800000) >> 23;
    unsigned int frac = (x & 0x007fffff);

    return (sign << 31) | (expo << 23) | frac;
}

I'm unsure however how I could compute the halved or doubled values from this floating point representation.

unsigned doubled(unsigned x) {
    // get float
    // float = unsigned int to float
    // doubleFloat  = 2*f
    // if float is not a number
        // return unsigned float
    // else return unsigned integer of half float

    unsigned int sign = (x & 0x80000000) >> 31;
    unsigned int expo = (x & 0x7F800000) >> 23;
    unsigned int frac = (x & 0x007fffff);

    if (expo == 0xff)
        return uf;
    else ...
}

Upvotes: 6

Views: 587

Answers (1)

Amadeus
Amadeus

Reputation: 10695

It seems that you are using IEEE 754 to represent Float values.

If you want to double the binary representation, you just need to increment by 1 the expoent. The same is true if you want to half, just decrement by 1

Remember that this is true only if your number is in normal range, including even after doubling or halving

Upvotes: 6

Related Questions