#include <iostream> #include <regex> #include <stdint.h> #include <stdio.h> #include <sstream> using namespace std; bool valid(string str){ const regex pattern("[0-9a-fA-F]{2} [0-9a-fA-F]{2} [0-9a-fA-F]{2} [0-9a-fA-F]{2}"); return regex_match(str,pattern); } bool parse(string str,float &f){ uint32_t num; for(string::iterator itr=str.begin();itr!=str.end();itr++) { if(*itr==' '){ str.erase(itr); } } str="0x"+str; sscanf(str.c_str(),"%x",&num); f=*((float*)&num); cout<<f<<endl; } std::string ieee_float_to_hex( float f ) { static_assert( std::numeric_limits<float>::is_iec559, "必須輸入符合的浮點數" ) ; union { float fval ; std::uint32_t ival ; }; fval = f ; std::ostringstream stm ; stm << std::hex << std::uppercase << ival<<endl; return stm.str() ; } void display(){ std::cout<<"* 1.選0,float------>int; *"<<endl; std::cout<<"* 1.選1,int------>float; *"<<endl; std::cout<<"* 1.選2,直接退出 *"<<endl; std::cout<<"* *"<<endl; std::cout<<"************************************************"<<endl; std::cout<<"請選擇:"; } int main(int argc, char const* argv[]) { string str; int select; float f; unsigned char byte[4]; while(true) { display(); cin>>select; switch(select) { case 0: std::cout<<"請輸入數字 (int 四位輸入時隔空格,由低位字節向高位字節排序"<<endl; std::cout<<"數字:"; getchar(); getline(cin,str); parse(str,f); break; case 1: cout<<"請輸入一個浮點數"; std::cout<<"輸入:"; cin>>f; cout<<ieee_float_to_hex(f); case 2: return 0; } } return 0; }