给定代表IEEE 754浮点数的32位,如何使用表示上的整数或位操作(而不是使用机器指令或编译器操作进行转换)将数字转换为整数?
我有以下功能,但在某些情况下失败:
输入:int x(包含IEEE 754格式的32位单精度数)
if(x == 0) return x;
unsigned int signBit = 0;
unsigned int absX = (unsigned int)x;
if (x < 0)
{
signBit = 0x80000000u;
absX = (unsigned int)-x;
}
unsigned int exponent = 158;
while ((absX & 0x80000000) == 0)
{
exponent--;
absX <<= 1;
}
unsigned int mantissa = absX >> 8;
unsigned int result = signBit | (exponent << 23) | (mantissa & 0x7fffff);
printf("\nfor x: %x, result: %x",x,result);
return result;
Run Code Online (Sandbox Code Playgroud) 现在,这是我应该实现的函数的函数头:
/*
* float_from_int - Return bit-level equivalent of expression (float) x
* Result is returned as unsigned int, but
* it is to be interpreted as the bit-level representation of a
* single-precision floating point values.
* Legal ops: Any integer/unsigned operations incl. ||, &&. also if, while
* Max ops: 30
* Rating: 4
*/
unsigned float_from_int(int x) {
...
}
Run Code Online (Sandbox Code Playgroud)
我们不允许进行浮动操作或任何类型的铸造.
现在我尝试实现在这个站点给出的第一个算法:http://locklessinc.com/articles/i2f/
这是我的代码:
unsigned float_from_int(int x) {
// grab sign bit
int xIsNegative = …Run Code Online (Sandbox Code Playgroud) 我正在使用floats 在 Cuda 中进行计算。由于 GPU 上没有足够的内存,因此我们将原始数据存储在 GPU 上uint16_t。int16_t因此,在使用这些数据之前,我必须将其转换为floats。s的数量int并没有那么大(大约 12kuint16_t和 相同数量int16_t)。分析显示,转换数字需要相当长的时间(大约 5-10%)。其余的计算无法进一步优化。因此我的3+1问题是:
int将s 转换为s的最快方法是什么float。int16_t转换或.时是否有实质性差异uint16_t?int转换较大类型(例如int32或 )时是否存在实质性差异int64?floats 转换为ints. 这是人们通常不会做的事情吗?