Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting float to an int (float2int) using only bitwise manipulation

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;
}

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

For example:

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

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

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.

There is also the issue of if the float cannot be represented as an integer (because it overflows or is a NaN).

Any help would be appreciated!

like image 331
0000101010 Avatar asked Jul 31 '26 11:07

0000101010


1 Answers

// 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;
}
like image 166
chux - Reinstate Monica Avatar answered Aug 03 '26 00:08

chux - Reinstate Monica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!