-------------------------------------
典型例题 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
计算机进制问题---浮点数转换为二进制数
最新推荐文章于 2023-03-02 12:12:00 发布