计算机进制问题---浮点数转换为二进制数

这是一个关于将浮点数转换为二进制和十六进制的程序实现。代码包括了double2bin和float2bin函数,通过归一化、指数偏置和 mantissa 转换进行浮点数到二进制的转换,并进一步将二进制转换为十六进制。程序展示了如何处理不同大小的浮点数,以及如何处理二进制和十六进制表示中的符号、指数和尾数部分。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

-------------------------------------
典型例题 27:计算机进制问题---浮点数转换为二进制数
-------------------------------------
 1    // double2bin.cc
 2    #include <iostream>
 3    #include <math.h>
 4   
 5    using namespace std;
 6   
 7    void normalize(double &f,char &e)
 8    {
 9        e = 0;
10   
11        // numbers larger than 2 we reduce
12        // down to 1 plus a fraction,
13        // and a compensating exponent
14        while(fabs(f) > 2)
15            {
16                f /= 2;
17                e++;
18            }
19   
20        // numbers smaller than 1 we promote
21        // up to 1 plus a fraction,
22        // and a compensating exponent
23        while(fabs(f) < 1)
24            {
25                f *= 2;
26                e--;
27            }
28    }
29   
30    void double2bin(double f,char *b)
31    {
32        char e1;
33        int e;
34        int i;
35   
36        normalize(f,e1);
37   
38        // add the bias
39        e = int(e1) + 1023;
40   
41        // set the sign bit
42        b[0] = (f < 0) ? '1':'0';
43   
44        f = fabs(f);
45   
46        // remove the leftmost 1 bit
47        f -= 1;
48   
49        b[1]=b[13]=' ';
50   
51        // convert the exponent
52        for(i=11;i>0;i--)
53            {
54                b[i+1] = e%2 + '0';
55                e/=2;
56            }
57   
58        // c

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值