转换INT浮在C(无铸造) [英] Convert int to float in C (no casting)

查看:199
本文介绍了转换INT浮在C(无铸造)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何把一个int为float(返回为无符号,但PTED为float间$ P $)?我不能使用任何高级语言结构,如工会,只能按位老年退休金计划,控制逻辑(如果/当)+和 - 等

How do I convert an int to a float (returned as unsigned, but interpreted as a float)? I can't use any high level language constructs like unions, only bitwise ops, control logic (if/while), + and -, etc.

推荐答案

当然。你当然可以从一个原始字节的缓冲区构建一个浮点数。单precision 浮动,则重新在IEEE-754 psented为32位值$ P $,并且可以在整数空间很容易地重新present。该维基百科上的IEEE浮点作品描述了各种格式。所有你需要做的就是找​​出哪些位设置或测试。看维基百科页面上单precision 一个不错的位的描述。这里有一个启动:

Sure. You can certainly construct a floating point number from a raw byte buffer. Single precision floats are represented as 32-bit values in IEEE-754 and can represent the integer space quite easily. The wikipedia entry on IEEE floating point describes the various formats. All that you have to do is figure out which bits to set or test. Look at the wikipedia page on single-precision for a nice description of the bits. Here's a start:

float convert_int(unsigned int num) {
    float result;
    unsigned int sign_bit = (num & 0x80000000);
    unsigned int exponent = (num & 0x7F800000) >> 23;
    unsigned int mantissa = (num & /* insert mask value here */);

    /* you can take over from here */

    return result;
}

我留下了许多到想象,但我有一种感觉,这是一个家庭作业的问题。一旦你明白,我已经写了一部分,它应该很容易做休息。一个好得多的解决方案是使用联盟,但我会离开,作为一个的读者做练习的为好。

I left a lot up to the imagination, but I have a feeling that this is a homework problem. Once you understand the part that I have written, it should be easy enough to do the rest. A much nicer solution is to use a union, but I will leave that as an exercise to the reader as well.

这篇关于转换INT浮在C(无铸造)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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