User:Chaser Zaks/IEEE-754

From Second Life Wiki
Jump to navigation Jump to search

Licensed under public domain

Encoder

integer floatToInteger(float input){
    if(input == 0.0) return 0;
    
    integer sign;
    float fnorm;
    if(input < 0){
        sign = 1;
        fnorm = -input;
    }else{
        sign = 0;
        fnorm = input;
    }

    integer shift = 0;
    while(fnorm++ >= 2.0) fnorm /= 2.0;
    while(fnorm-- < 1.0) fnorm *= 2.0;
    
    return (sign<<31) //Sign
         | ((shift + ((1<<7) - 1))<<23) //exponent
         | (integer)((fnorm - 1.0) * ((float)(1<<23) + 0.5)); //fraction
}

Decoder

float integerToFloat(integer input){
    integer sign = 1;
    if(input & 0x80000000) sign = -1;
    
    integer pow = -1;
    float val = 0.0;
    integer i = 9;
    for(; i < 32; i++)
        val += (float)(((input >> 31 - i) & 1)) * (float)llPow(2.0, pow--);
    
    return sign * (float)llPow( 2.0, ((input & 0x7f800000) >> 23) - 127) * (val + 1.0);
}

Also see