[英]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).我有一个用 Python 编写的函数,它非常适合我的需要(不是我写的)。 I need to convert it to C++ so that it provides the same outcome.
我需要将它转换为 C++,以便它提供相同的结果。 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.
我知道它将浮点数保存为 16 位纹理,所以我猜这是将 32 位 int 转换为 16 位浮点数。 All I need to to is to make it work in C++.
我需要做的就是让它在 C++ 中工作。 Here is the python function:
这是python函数:
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:这是我在 C++ 中的方法,但它返回完全搞砸的值:
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.
我的 C++ 解决方案 100% 有效。 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.
我尝试将浮点数推入纹理,它是 16 位纹理。 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.
称为 PF_FloatRGBA 的纹理标志让我相信浮点数是在那里分配的正确事物,但它们不是。
I still need to learn a lot.我还需要学习很多东西。 Thanks for all your help!
感谢你的帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.