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.