StringStream in C++ for Decimal to Hexadecimal and back

Stringstream is stream class present in C++ which is used for doing operations on a string. It can be used for formatting/parsing/converting a string to number/char etc.
Hex is an I/O manipulator that takes reference to an I/O stream as parameter and returns reference to the stream after manipulation.
Here is a quick way to convert any decimal to hexadecimal using stringstream:

// CPP program to convert integer to
// hexadecimal using stringstream and
// hex I/O manipulator.
#include <bits/stdc++.h>
using namespace std;

int main()
{
    int i = 942;
    stringstream ss;
    ss << hex << i;
    string res = ss.str();
    cout << "0x" << res << endl; // this will print 0x3ae
    return 0;
}

Output:

0x3ae

If we want to change hexadecimal string back to decimal you can do it by following way:

// CPP program to convert hexadecimal to
// integer using stringstream and
// hex I/O manipulator.
#include <bits/stdc++.h>
using namespace std;

int main()
{
    string hexStr = "0x3ae";
    unsigned int x;
    stringstream ss;
    ss << std::hex << hexStr;
    ss >> x;
    cout << x << endl; // this will print 942
    return 0;
}

Output:

942




Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Recommended Posts:



0 Average Difficulty : 0/5.0
No votes yet.