相关疑难解决方法(0)

在C中将float转换为int(按位)

给定代表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)

c floating-point bit-manipulation bitwise-operators

13
推荐指数
6
解决办法
3万
查看次数

如何手动(按位)执行(浮点)x?

现在,这是我应该实现的函数的函数头:

/*
 * 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)

c floating-point casting bit-manipulation

8
推荐指数
1
解决办法
1万
查看次数