我想知道是否有人可以针对我正在处理的问题为我指明正确的方向。我正在尝试仅使用 ARM 汇编和位操作来执行以下 C 函数的操作:
int float2int(float x) {
return (int) x;
}
我已经编写了这个 (int2float) 的反向代码,没有很多问题。我只是不确定从哪里开始解决这个新问题。
例如:
3 (int) = 0x40400000 (float)
0011 = 0 10000000 10000000000000000000000
其中 0 是符号位,10000000 是指数,10000000000000000000000 是尾数/分数。
有人可以简单地指出我解决这个问题的正确方向吗?即使是 C 伪代码表示也会有所帮助。我知道我需要提取符号位、指数并反转偏差 (127) 以及提取分数,但我不知道从哪里开始。
还有一个问题是 float 是否不能表示为整数(因为它溢出或者是 NaN)。
如有任何帮助,我们将不胜感激!
最佳答案
// Assume int can hold all the precision of a float.
int float2int(float x) {
int Sign = f_SignRawBit(x);
unsigned Mantissa = f_RawMantissaBits(x); // 0 - 0x7FFFFF
int Expo = f_RawExpoBits(x); // 0 - 255
// Form correct exponent and mantissa
if (Expo == EXPO_MAX) {
Handle_NAN_INF();
}
else if (Expo == EXPO_MIN) {
Expo += BIAS + 1 - MantissaOffset /* 23 */;
}
else {
Expo += BIAS - MantissaOffset /* 23 */;
Mantissa |= ImpliedBit;
}
while (Expo > 0) {
Expo--;
// Add code to detect overflow
Mantissa *= 2;
}
while (Expo < 0) {
Expo++;
// Add code to note last shifted out bit
// Add code to note if any non-zero bit shifted out
Mantissa /= 2;
}
// Add rounding code depending on `last shifted out bit` and `non-zero bit shifted out`. May not be need if rounding toward 0.
// Add code to detect over/under flow in the following
if (Sign) {
return -Mantissa;
}
return Mantissa;
}
关于仅使用按位操作将 float 转换为 int (float2int),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20318911/