存储整数作为花车 [英] Storing ints as floats

查看:105
本文介绍了存储整数作为花车的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个API,只允许我存储花车,彩车或数组。不过,我想在这里存储的整数值。

Suppose I have an API that only allows me to store floats, or arrays of floats. However, I would like to be storing integer values here.

我(大致)明白,我是pretty还好用直投高达约2 ^ 23,但如果我想继续走高呢?有没有办法,我可以把更多的是浮动的32位的优势,并相信我会得到相同的回数什么办法?

I (roughly) understand that I am pretty okay with a straight cast up to around 2^23, but what if I want to go higher? Is there any way that I can take advantage of more of the 32 bits of a float and be sure I will get the same number back?

有关澄清:

我在做与皮克斯的PRMan(即RenderMan的)点云的一些操作。我可以用C或C ++链接对precompiled点云API编写。 PRMan在任何时候都有使用这些整数,我存储;我只需要它完整的附着点其他数据操作后把他们还给我。

I'm doing some operations on point clouds with Pixar's PRMan (ie. RenderMan). I can write in either C or C++ linking against the precompiled point cloud API. PRMan at no point has to use these ints I am storing; I only need it to hand them back to me intact after operating on other data attached to the points.

推荐答案

可疑:

在C,你可以做到以下几点,这是潜在的危险(由于严格走样规则):

In C, you can do the following, which is potentially unsafe (due to strict-aliasing rules):

int i = XXX;
float f;
*(int *)&f = i;

和依赖的假设是的sizeof(int)的==的sizeof(浮动)

减可疑的:

更安全,但更冗长,如下:

Safer, but more longwinded, is the following:

int i = XXX;
float f;
memcpy(&f, &i, sizeof(int));

这仍依赖于匹配的数据类型的大小。然而,无论是上述的作一个假设,你使用会做的在图书馆内部没有的在所有的数据。例如,它不会对NaN的任何特殊处理,或+/-无穷大,等等。

This still relies on matching data-type sizes. However, both of the above make the assumption that the internals of the library you're using will do nothing at all to the data. For instance, it won't have any special handling for NaN, or +/-infinity, etc.

安全:

随着一个完全不同的思路,如果你乐意浪费每INT两个浮点数,你可以这样做:

Along an entirely different train of thought, if you're happy to waste two floats per int, you could do something like:

int i = XXX;
float f[2] = { (i & 0xFFFF), ((unsigned)i >> 16 };

这最后一个是安全(除上花车和整数的大小一些pretty合理的假设)。

This last one is safe (other than some pretty reasonable assumptions on the size of floats and ints).

这篇关于存储整数作为花车的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆