Search code examples
cdouble-precisionexponent

c change the exponent of a double


Lets say I have a double a = 0.3;. How would I be able to change the exponent of the variable, without using math functions like pow(), or multiplying it manually.

I am guessing I would have to acces the memory addres of the variable using pointers, find the exponent and change it manualy. But how would I accomplish this?

Note, that this is on a 8-bit system, and I am trying to find a faster way to multiply the number by 10^12, 10^9, 10^6 or 10^3.

Best regards!


Solution

  • Note that a*10^3 = a*1000 = a*1024 - a*16 - a*8 = a*2^10 - a*2^4 - a*2^3.

    So you can calculate a*10^3 as follows:

    • Read the 11 exponent bits into int exp

    • Read the 52 fraction bits into double frac

    • Calculate double x with exp+10 as the exponent and frac as the fraction

    • Calculate double y with exp+4 as the exponent and frac as the fraction

    • Calculate double z with exp+3 as the exponent and frac as the fraction

    • Calculate the output as x-y-z, and don't forget to add the sign bit if a < 0

    You can use a similar method for the other options (a*10^6, a*10^9 and a*10^12)...


    Here is how you can do the whole thing in a "clean" manner:

    double MulBy1000(double a)
    {
        double x = a;
        double y = a;
        double z = a;
    
        unsigned long long* px = (unsigned long long*)&x;
        unsigned long long* py = (unsigned long long*)&y;
        unsigned long long* pz = (unsigned long long*)&z;
    
        *px += 10ULL << 52;
        *py +=  4ULL << 52;
        *pz +=  3ULL << 52;
    
        return x - y - z;
    }
    

    Please note that I'm not sure whether or not this code breaks strict-aliasing rules.