在不使用类型转换或库功能的情况下,必须使用位操作将整数转换为浮点型。下面是我当前正在处理的代码。它基于我在C中某些整数上使用位操作中断在Cast Integer to Float中找到的代码。我遇到的问题涉及IEEE 754中的四舍五入标准。更具体地说,我的代码四舍五入为0,但是应该四舍五入为偶数。我需要进行哪些更改?
unsigned inttofloat(int x) {
int bias = 127;
int man;
int exp = bias + 31; //8-bit exp
int count = 0;
int tmin = 1 << 31;
int manpattern = 0x7FFFFF;
int sign = 0;
if (x == 0){
return 0;
}
else if (x == tmin){
return 0xcf << 24;
}
if (x < 0) {
sign = tmin;
x = ~x + 1; // makes x negative so that we can accurately represent it later on.
}
while((x & tmin) == 0){
exp--;
x <<= 1;
count++;
}
exp <<= 23;
man = (x >> 8) & manpattern;
return (sign | exp | man);
}
要舍入到最接近的值-平整关系,请替换(x >> 8)
为:
unsigned u = x; // avoid any potential signed shifting issues
unsigned lease_significant_bit = (u >> 8) & 1;
unsigned round_bit = (u >> 7) & 1; // Most significant bit shifted out
unsigned sticky_bit_flag = !!(u & 0x7F); // All other bits shifts out
// OP's shifted answer.
u = (u >> 8):
// round away if more than half-way or
// if at half-way and number is odd
u += (round_bit & sticky_bit_flag) | (round_bit & lease_significant_bit);
留给OP简化
请注意,它u += 1
可能会一直传播,并且需要指数增加。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句