C++ 中的 StringStream 可將十進位制轉換為十六進位制,反之亦然


在本節中,我們將介紹如何在 C++ 中將十進位制轉換為十六進位制字串,以及如何將十六進位制字串轉換為十進位制字串。為此,我們將使用 C++ 的 stringstream 特性。

字串流用於格式化、解析、將字串轉換為數字值等。Hex 是一個 IO 處理器。它獲取對 IO 流的引用作為引數,並在處理後返回對字串的引用。

在以下示例中,我們將介紹如何轉換十進位制數或十六進位制數。

示例程式碼

#include<iostream>
#include<sstream>
using namespace std;
main(){
   int decimal = 61;
   stringstream my_ss;
   my_ss << hex << decimal;
   string res = my_ss.str();
   cout << "The hexadecimal value of 61 is: " << res;
}

輸出

The hexadecimal value of 61 is: 3d

在上面的示例中,我們使用提取運算子 “<<” 來獲取十進位制到十六進位制。在下一個示例中,我們將執行逆過程。在此示例中,我們將十六進位制字串轉換為十六進位制,然後使用插入運算子 “>>” 將字串流儲存到整數。

示例程式碼

using namespace std;
main() {
   string hex_str = "0x3d"; //you may or may not add 0x before
   hex value
   unsigned int decimal;
   stringstream my_ss;
   my_ss << hex << hex_str;
   my_ss >> decimal;
   cout << "The Decimal value of 0x3d is: " << decimal;
}

輸出

The Decimal value of 0x3d is: 61

更新於:30-Jul-2019

638 次瀏覽

開啟你的職業生涯

完成課程即可獲得認證

開始
廣告
© . All rights reserved.