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-


分享到:


相關文章: