代碼如下:
#include<iostream>
#include<vector>
#include"math.h"
#include<iomanip>
#include <algorithm>
using namespace std;
void fun(bool m)//列印
{
cout<<m;
}
vector<bool> get_hex_2b(unsigned int a)//將十六進制轉化成二進制
{
vector<bool> x;
for (int i=0;i<32;i++)
{
if((((int)a)&(0x80000000>>i)))
{
x.push_back(1);
}
else
{
x.push_back(0);
}
}
///////////////////////////////////列印十六進制的二進制碼
cout<<"二進制碼:"<<endl;
for_each(x.begin(),x.end(),fun);
cout<<endl;
/////////////////////////////////////
return x;
}
int get_hex_jiema(vector<bool> a)//引數為短浮點數的二進制碼
{
//將原來的二進制碼的1-8位裝到移碼容器中
vector<bool> yima(a.begin()+1,a.begin()+9);
vector<bool>::iterator ite=yima.begin();//設定容器的迭代器
unsigned int sum=0;
//計算二進制代碼表示的十進制數
for(int i=0;i<8;i++)
{
sum=sum+(*ite)*pow(2,7-i);
ite++;
}
int jiema=sum-127;
return jiema;
}
float get_10dec(vector<bool> a)//引數為短浮點數的二進制碼
{
//存整數部分的二進制 ,初始值中有一個1,為尾碼的隱含位
vector<bool> zhengshu(1,1);
vector<bool> xiaoshu;//存小數部分的二進制
//將原本的二進制代碼的9-尾位裝到尾碼容器中
vector<bool> weima(a.begin()+9,a.end());
//根據階碼大小,向左移位尾碼,得到整數的二進制代碼
zhengshu.insert(zhengshu.end(),weima.begin(),weima.begin()+get_hex_jiema(a));
//尾碼的剩余部分為小數的二進制代碼
xiaoshu.insert(xiaoshu.end(),weima.begin()+get_hex_jiema(a),weima.end());
//////////////////////////////////////////
//列印整數和小數部分的二進制碼
cout<<"整數部分:"<<endl;
for_each(zhengshu.begin(),zhengshu.end(),fun);
cout<<endl;
cout<<"小數部分:"<<endl;
for_each(xiaoshu.begin(),xiaoshu.end(),fun);
cout<<endl;
/////////////////////////////////////////////
float zheng_shu=0;
float xiao_shu=0;
float sum=0;
//計算整數的十進制大小
for(int i=zhengshu.size();i>0;i--)
{
zheng_shu=zheng_shu+zhengshu[i-1]*pow(2,zhengshu.size()-i);
}
//計算小數的十進制大小
for(int i=0;i<xiaoshu.size();i++)
{
xiao_shu=xiao_shu+xiaoshu[i]*pow(2,-(i+1));
}
sum=zheng_shu+xiao_shu;
//判斷符號位
if(a[0]==1)
sum=0-sum;
return sum;
}
int main()
{
unsigned int a;
float sum=0;
int e=0;
cout<<"請輸入要轉化成是十進制的IEEE754標準的短浮點數的十六進制形式:" <<endl;
cin>>hex>>a;//十六進制輸入
e= get_hex_jiema(get_hex_2b(a));
cout<<"階碼的大小:"<<e<<endl;
sum=get_10dec(get_hex_2b(a));
cout<<"轉換成十進制數為:"<<endl;
cout<<sum<<endl;
cout<<endl;
system("pause");
return 0;
}
終端報錯:
請輸入要轉化成是十進制的IEEE754標準的短浮點數的十六進制形式:
be55b000
二進制碼:
10111110010101011011000000000000
階碼的大小:-3
二進制碼:
10111110010101011011000000000000
terminate called after throwing an instance of 'std::length_error'
what(): vector<bool>::_M_insert_range
已放棄 (核心已轉儲)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/166940.html
標籤:C++ 語言
上一篇:c++binary_function使用結構體//為什么找不到<運算子?
下一篇:新手,求助!求圓體積錯誤
