按位浮点到整数 [英] Bitwise Float To Int

查看:94
本文介绍了按位浮点到整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试找出算法,但是我在google上得到的全部是通过强制转换来实现的.我需要知道细节.

I am trying to figure out the algorithm to this but all I get with google is doing it with casting. I need to know the details.

因此,如果我们有一个float x并想返回其二进制表示形式,那我们需要做什么?

So if we have a float x and want to return its binary representation what do we need to do?

我知道我们需要返回浮点数(如果其NaN或无穷大),但是返回步骤是什么?

I know we need to return the float if its NaN or a infinity but otherwise what are the steps?

编辑

该函数将一个无符号的int用作浮点数,然后返回该数字表示的整数.我不能使用强制转换,只能使用条件运算符和按位运算符.

The function takes in an unsigned int, to be used as if it was a float, and then return the integer the number represents. I cannot use casting, just conditionals and bit-wise operators.

推荐答案

或者,使用联合:

typedef union 
{
    float f_;
    int   i_;
} FloatBits;

FloatBits fb;

fb.f_ = 1.5;

然后,fb.i_包含映射到int的浮点数,以允许提取位.同样,关于类型大小的常见假设-您可以使用sizeof进行验证.

Then fb.i_ contains the float mapped onto an int to allow extraction of the bits. Again, usual assunptions about the size of types - you can verify these using sizeof.

使用这种方法,您可以直接设置fb.i_中的位,然后将它们映射回float中.

Using this approach, you can play with setting the bits in fb.i_ directly and seeing them mapped back into the float.

这篇关于按位浮点到整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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