仅使用按位操作将 float 转换为 int (float2int) [英] Converting float to an int (float2int) using only bitwise manipulation

查看:29
本文介绍了仅使用按位操作将 float 转换为 int (float2int)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有人可以让我朝着正确的方向解决我正在解决的问题.我正在尝试仅使用 ARM 汇编和位操作来执行以下 C 函数所做的操作:

I am wondering if someone could set me in the right direction with a problem I am working on. I am trying to do what the following C function does using only ARM assembly and bit manipulation:

int float2int(float x) {
return (int) x;
}

我已经对这个 (int2float) 进行了反向编码,没有太多问题.我只是不确定从哪里开始解决这个新问题.

I have already coded the reverse of this (int2float) without many issues. Im just unsure of where to start with this new problem.

例如:

3 (int) = 0x40400000 (float) 
0011 = 0 10000000 10000000000000000000000

其中 0 是符号位,10000000 是指数,10000000000000000000000 是尾数/分数.

Where 0 is the Sign Bit, 10000000 is the exponent, and 10000000000000000000000 is the mantissa/fraction.

有人可以简单地为我指出这个问题的正确方向吗?即使是 C 伪代码表示也会有帮助.我知道我需要提取符号位、提取指数并反转偏置 (127) 并提取分数,但我不知道从哪里开始.

Can someone simply point me in the right direction with this problem? Even a C pseudocode representation would be helpful. I know I need to extract the sign bit, extract the exponent and reverse the bias (127) and also extract the fraction but I just have no idea where to begin.

如果浮点数不能表示为整数(因为它溢出或为 NaN),也存在一个问题.

There is also the issue of if the float cannot be represented as an integer (because it overflows or is a 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)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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