C++ 十進制 與 八進制、十六進制 互轉


#include <iostream>
#include <sstream>
using namespace std;

int main()
{
/*----------------------------------
    十六進制,八進制轉十進制
----------------------------------*/
    int decimal1,decimal2;
    string oct_test = "75";
    string hex_test = "A3";

    stringstream ss1;
    
    ss1.str(oct_test);
    ss1>>oct>>decimal1;
    cout<<"Convert oct to decimal:"<<decimal1<<endl;

    //ss1.clear();//若不想從新定義stringstream流,必須先清空ss1中的緩存
    stringstream ss2;
    ss2.str(hex_test);
    ss2>>hex>>decimal2;
    cout<<"Convert hex to decimal:"<<decimal2<<endl;

/*----------------------------------
    十進制轉八進制、十六進制
----------------------------------*/
    int decimal;
    stringstream ss,sss;
    cout<<"Enter a decimal number:";
    cin>>decimal;
    /*下面兩句等價於:
    cout<<"Convert to hex:"<<hex<<decimal<<endl;
    */
    //十進制轉十六進制
    ss<<hex<<decimal;
    cout<<"Convert to hex:"<<ss.str()<<endl;
    //十進制轉八進制
    ss.str(""); //同上,若不想從新定義stringstream流,必須先將ss.str()置為空
    ss<<oct<<decimal;
    cout<<"Convert to oct:"<<ss.str()<<endl;


    system("pause");
    return 0;
}

運行結果如下:

 

十六進制結果控制:

將:
ss<<hex<<decimal;
替換為:
ss << "0x" << uppercase << setfill('0') << setw(4) << std::hex << decimal;
uppercase : 將小寫轉大寫;  setfill('0'): 填充0;  setw(4): 設置位寬為4 

這里要加入頭文件 #include <iomanip>

 

再次運行結果為:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM