在C中将float转换为int(按位) [英] Casting float to int (bitwise) in C

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

问题描述

给定代表 IEEE 754 浮点数的 32 位,如何将数字转换为整数,在表示上使用整数或位操作(而不是使用机器指令或编译器操作进行转换)?

Given the 32 bits that represent an IEEE 754 floating-point number, how can the number be converted to an integer, using integer or bit operations on the representation (rather than using a machine instruction or compiler operation to convert)?

我有以下功能,但在某些情况下会失败:

I have the following function but it fails in some cases:

输入:int x(包含 IEEE 754 格式的 32 位单精度数)

Input: int x (contains 32 bit single precision number in IEEE 754 format)

  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("
for x: %x, result: %x",x,result);
  return result;

推荐答案

C 有联合"来处理这种类型的数据视图:

C has the "union" to handle this type of view of data:

typedef union {
  int i;
  float f;
 } u;
 u u1;
 u1.f = 45.6789;
 /* now u1.i refers to the int version of the float */
 printf("%d",u1.i);

这篇关于在C中将float转换为int(按位)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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