简体   繁体   中英

Int to Float conversion Python to C++

I have a function written in Python that works perfectly for what I need(it wasn't written by me). I need to convert it to C++ so that it provides the same outcome. I know that it saves that float into 16-bit texture, so I am guessing this is converting 32-bit int into 16-bit float. All I need to to is to make it work in C++. Here is the python function:

def packTextureBits(index):
    index = int(index)
    index = index +1024
    sigh=index&0x8000
    sigh=sigh<<16
    exptest=index&0x7fff
    if exptest==0:
        exp=0
    else:
        exp=index>>10
        exp=exp&0x1f
        exp=exp-15
        exp=exp+127
        exp=exp<<23
    mant=index&0x3ff
    mant=mant<<13
    index=sigh|exp|mant
    
    cp = pointer(c_int(index))
    fp = cast(cp, POINTER(c_float))
    return fp.contents.value

This was my approach in C++, but it returns completely screwed up values:

float PackIntToFloat(int value)
{
    value += 1024;
    int sign = (value & 0x8000) << 16;
    int exp = value & 0x7fff;
    if(exp != 0)
    {
        exp = value >> 10;
        exp = exp & 0x1f;
        exp = exp - 15 + 127;
        exp = exp << 23;
    }
    int mant = (value & 0x3fff) << 13;
    value = sign | exp | mant;

    int* cp = new int(value);
    float* fp = reinterpret_cast<float*>(cp);

    return *fp;
    // Also tried return (float)value; but returns other weird values.
}

So I owe you apologize guys. I was being stupid, not doing enough tests before posting here. My C++ solution is 100% working. I tested separate colors of the texture, and as it turned out, I assigned values to the texture the wrong way. I tried pushing floats into the texture, and it was 16 bit texture. I needed to convert these floats into half-precision floats after this conversion above, and then it started working. Texture flag called PF_FloatRGBA led me into believing that floats were the right thing to assign there, and they werent.

I still need to learn a lot. Thanks for all your help!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM