C++|三种方式输出浮点数的二进制位

对于浮点数,一般遵循IEEE574的规则,使用符号位+阶码(移码)+尾码;

我们知道,要输出浮点数的二进制位,我们需要进行位运算,而位运算的对象只能是unsigned。(bitset容器的初始值也只能使用unsigned)为此,有以下三种方式可以输出浮点数的二进制位:

1 union共用体+位运算

//位运算结合union输出int和float的二进制位
#include <iostream>
using namespace std;
union { //用于将浮点数的二进制位解析为int位输出
\tfloat input;
\tint output;
} data;
void int2binary(unsigned n)//位运算只能用于整形
{
\tunsigned b32 = 1<<31;//32位二进制,最高位是1,其它位是0
\tcout<>31)<\tfor(int i=1;i<32;++i)
\t{
\t\tn=n<<1;//循环左移一位,用于最高位的与运算
\t\tcout<>31);//最高位与运算,移位后最高位输出
\t\tif(i==7)
\t\t\tcout<\t\tif(i>8 && (i-7)%8==0)
\t\t\tcout<\t}
\tcout<}
void float2binary(unsigned n)
{
\tunsigned b32 = 1<<31;//32位二进制,最高位是1,其它位是0
\tcout<>31)<\tfor(int i=1;i<32;++i)
\t{
\t\tn=n<<1;//循环左移一位,用于最高位的与运算

\t\tcout<>31);//最高位与运算,移位后最高位输出
\t\tif(i%8==0)
\t\t\tcout<\t}
\tcout<}
void main()
{
\twhile(1)
\t{
\t\tint n;
\t\tcout<\t\tcin>>n;
\t\tint2binary(n);
\t\tcout<<endl>\t\tcout<\t\tcin>>data.input;
\t\tfloat2binary(data.output);
\t\tcout<<endl>\t}
}
/*
please input a int:178
0 0000000 00000000 00000000 10110010
please input a float:178.625
0 10000110 01100101 01000000 0000000
please input a int:-178
1 1111111 11111111 11111111 01001110
please input a float:-178.625
1 10000110 01100101 01000000 0000000
please input a int:134
0 0000000 00000000 00000000 10000110
please input a float:
10110010的阶数是7,最高位总是1,直接隐藏掉;
阶码=阶数+偏移量
=阶数+2^(e-1)-1
=阶数+2^(8-1)-1
=7+127
=134(10000110)

*/
/<endl>/<endl>/<iostream>

2 union结合bitset输出浮点数的二进制位


//union结合bitset输出浮点数的二进制位
#include <iostream>

#include <bitset>
using namespace std;
union { //用于将浮点数的二进制位解析为int位输出
\tfloat input;
\tint output;
} data;
void float2binary(unsigned n)
{
\tunsigned b32 = 1<<31;//32位二进制,最高位是1,其它位是0
\tcout<>31)<\tfor(int i=1;i<32;++i)
\t{
\t\tn=n<<1;//循环左移一位,用于最高位的与运算
\t\tcout<>31);//最高位与运算,移位后最高位输出
\t\tif(i%8==0)
\t\t\tcout<\t}
\tcout<}
void main()
{
\twhile(1)
\t{
\t\tcout<\t\tcin>>data.input;
\t\tbitset<32> bs(data.output);//将整数放到一个32位的位容器内
\t\tcout<\t}
}
/<bitset>/<iostream>

3 将浮点数的二进制位memcopy给unsigned int

#include <iostream>
#include <string.h>
using namespace std;
void main()
{
\tfloat data;
\tunsigned long buff;
\tchar s[34];
\tdata = (float)0.75;//字面浮点数默认是按double处理

\tmemcpy(&buff,&data,4);//把浮点数编码的二进制位复制给用整数编码的地址
\tfor(int i=33;i>=0;i--)//按位处理整数的二进制位
\t{
\t\tif(i==1 || i==10)
\t\t\ts[i]=' ';
\t\telse
\t\t{
\t\t\tif(buff%2==1)
\t\t\t\ts[i] = '1';
\t\t\telse
\t\t\t\ts[i] = '0';
\t\t\tbuff/= 2;
\t\t}
\t}
\ts[34] = '\\0';
\tcout< system("pause");
}
/<string.h>/<iostream>

-End-


分享到:


相關文章: