如何从十进制数转换为 IEEE 754 单精度浮点格式? [英] How do I convert from a decimal number to IEEE 754 single-precision floating-point format?

查看:42
本文介绍了如何从十进制数转换为 IEEE 754 单精度浮点格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何手动将十进制(以 10 为基数)数字更改为 IEEE 754 单精度浮点格式?我知道它由三个部分组成,一个符号,一个指数和一个尾数.我只是不完全理解最后两部分实际代表什么.

How would I go about manually changing a decimal (base 10) number into IEEE 754 single-precision floating-point format? I understand that there is three parts to it, a sign, an exponent, and a mantissa. I just don't completely understand what the last two parts actually represent.

推荐答案

找到比你的数字小的 2 的最大幂,例如,如果你从 x = 10.0 开始,那么 23 = 8,所以指数为 3.指数偏置 127,因此这意味着指数将表示为 127 + 3 = 130.尾数为 10.0/8 = 1.25.1 是隐含的,所以我们只需要表示 0.25,即 010 0000 0000 0000 0000 0000 表示为 23 位无符号小数.符号位为 0 表示正数.所以我们有:

Find the largest power of 2 which is smaller than your number, e.g if you start with x = 10.0 then 23 = 8, so the exponent is 3. The exponent is biased by 127 so this means the exponent will be represented as 127 + 3 = 130. The mantissa is then 10.0/8 = 1.25. The 1 is implicit so we just need to represent 0.25, which is 010 0000 0000 0000 0000 0000 when expressed as a 23 bit unsigned fractional quantity. The sign bit is 0 for positive. So we have:

s | exp [130]  | mantissa [(1).25]            |

0 | 100 0001 0 | 010 0000 0000 0000 0000 0000 |

0x41200000

您可以使用简单的 C 程序来测试表示,例如

You can test the representation with a simple C program, e.g.

#include <stdio.h>

typedef union
{
    int i;
    float f;
} U;

int main(void)
{
    U u;
    
    u.f = 10.0;
    
    printf("%g = %#x
", u.f, u.i);

    return 0;
}

这篇关于如何从十进制数转换为 IEEE 754 单精度浮点格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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