StringStream in C++ for Decimal to Hexadecimal and back


In this section we will see how to convert Decimal to Hexadecimal string and also from Hexadecimal string to Decimal string in C++. For this conversion we are using the stringstream feature of C++.

String streams are used for formatting, parsing, converting a string into numeric values etc. The Hex is an IO manipulator. It takes reference to an IO stream as parameter and returns reference to the string after manipulating it.

In the following example we will see how to convert decimal number or hexadecimal number.

Example Code

#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;
}

Output

The hexadecimal value of 61 is: 3d

In the above example we are using extraction operator “<<” to get decimal to hex. In the next example we will do the reverse. In this example We will convert hex string to hex, then using insertion operator “>>” we store string stream to an integer.

Example Code

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;
}

Output

The Decimal value of 0x3d is: 61
raja
Published on 04-Apr-2019 13:16:41
Advertisements