IEEE-754标准(32位)十六进制转十进制浮点数
#include<fstream>
#include <sstream>
#include <iostream>
#include<math.h>
using namespace std;double BtoD(string x)
{double ans;int E = 0;double D = 0;for (int i = 1; i < 32; i++){if (i < 9){E += (x[i] - '0') << (8 - i);}else{D += (x[i] - '0') * pow(2 ,(8 - i));}}ans = pow(2, E - 127)*(1+D);if (x[0] = '1')ans = -ans;return -ans;
}int main()
{string input;ifstream in;in.open("D:\\p1.txt");if (!in.good()){cout << "文件打开失败" << endl;system("pause");return 0;}while (!in.eof()){in >> input;cout << input << endl;;cout << BtoD(input) << endl;system("pause");}in.close();cout << "转换完成" << endl;system("pause");return 0;}
十进制浮点数 转IEEE-754标准(32位)十六进制
#include<iostream>
#include<vector>
#include"math.h"
#include<iomanip>
#include <fstream>using namespace std;vector<bool> zhengshu;
vector<bool> xiaoshu;vector<bool> get_zhengshu_2b(float a)
{vector<bool> x;x.clear();for (int i = 0; i < 8; i++){if ((((int)a)&(0x80 >> i))){x.push_back(1);}else{x.push_back(0);}}return x;
}void get_2b(float a)
{float fabs_a = fabs(a);zhengshu.clear();xiaoshu.clear();zhengshu = get_zhengshu_2b(fabs_a);float n = 2; float b = (fabs_a - floor(fabs_a));while (!b == 0){if ((1.0 / n) < b){xiaoshu.push_back(1);b = b - (1.0 / n);}else if ((1.0 / n) > b){xiaoshu.push_back(0);}else if ((1.0 / n) == b){xiaoshu.push_back(1);break;}n = n * 2;}
}
int get_jiema()
{for (int i = 0; i < 8; i++){if (zhengshu[i] == 1)return 7 - i; }
}
vector<bool> get_yima()
{int e = get_jiema();e = e + 127; return get_zhengshu_2b(e);
}
vector<bool> get_weima()
{vector <bool> m;xiaoshu.insert(xiaoshu.begin(), zhengshu.begin() + (8 - get_jiema()), zhengshu.end());m = xiaoshu;return m;
}
vector<bool> to_IEEE754(float x)
{vector<bool> IEEE;IEEE.clear();get_2b(x); vector<bool> yima;yima.clear();yima = get_yima();vector<bool> weima;weima.clear();weima = get_weima();if (x > 0){IEEE.insert(IEEE.end(), 1, 0);}else{IEEE.insert(IEEE.end(), 1, 1);}IEEE.insert(IEEE.end(), yima.begin(), yima.end());IEEE.insert(IEEE.end(), weima.begin(), weima.end());IEEE.insert(IEEE.end(), 32 - 9 - weima.size(), 0);return IEEE;
}
void get_hex(vector<bool> E)
{ofstream out;out.open("D:\\Desktop\\输出.txt", ios::app);vector<bool>::iterator ite = E.begin();int sum = 0;int n = 8;while (n--){for (int i = 0; i < 4; i++){sum = sum + (*ite)*pow(2, 3 - i);ite++;}cout << setiosflags(ios::uppercase) << hex << sum;out << setiosflags(ios::uppercase) << hex << sum;sum = 0;}out << endl;out.close();cout << endl;
}int main()
{ifstream in;in.open("D:\\P1.txt");if (!in.good()){cout << "文件打开失败" << endl;system("pause");return 0;}while (!in.eof()){float x;vector<bool> IEEE;in >> x;cout << x <<"转换为:" ;IEEE = to_IEEE754(x);get_hex(IEEE);IEEE.clear();cout << endl;}in.close();cout << "转换完成" << endl;system("pause");return 0;}