How to convert float to uint32 according to ieee 754 ?



  • Hello,

    I'm trying to convert a float number to a uint16_t[2], according the IEEE 754 format.

    For example, I manage to do the contrary :
    @
    double uint16t2double(uint16_t* buff)
    {
    uint32_t test32 = 0;
    test32 = buff[0];
    int i;
    double resultat;

    test32 = test32 << 16;
    
    test32 = test32 + buff[1];
    
    char sign;
    signe = test32 >> 31;
    
    unsigned char expo;
    expo = (test32 & 0x7F800000) >> 23;
    expo -= 127;
    
    uint32_t mantissa = (test32 & 0x7FFFFF);
    float m = 1;
    for(i=1; i<=23; i++) {
        if((mantissa & 0x400000) != 0) {
            m += pow(2, -i);
        }
        mantissa = mantissa << 1;
    }
    
    result = pow((double)2,(double)expo);
    if(sign)
        result = -1*result * m;
    else
        result = result * m;
    
    return result;
    

    }
    @

    Can anyone help me ?

    PS: I'm new on forum, please excuse me if my message is not in the proper section and my explanations too succinct.



  • I suspect you haven't gotten an answer because it's hard to tell what you're asking without doing a thorough analysis of the code. You appear to create a 32 bit number out of a passed array of two 16 bit numbers using the first item in memory as the MSB and the second as the LSB. Then it's not clear why you don't just then use:
    @double result = static_cast<double>(test32);
    return result;@

    Going by the title of the post if I wanted to convert a float to a 32 bit integer I would check that the passed value would fit then
    @uint_32t result = static_cast<uint32_t>(passed_double);
    return result;@

    Actually I would return a std:pair<bool, uint32_t> to make it obvious to the caller that they have to check the validity of the returned result.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.