StringStream in C++ for Decimal to Hexadecimal and back Last Updated : 14 Feb, 2023 Comments Improve Suggest changes 7 Likes Like Report 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 // 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 The time complexity of this program is O(1) as it only performs a single operation. The space complexity is also O(1) as no additional space is used. If we want to change hexadecimal string back to decimal you can do it by following way: CPP // 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 Time Complexity: The time complexity of the above algorithm is O(1), as we are only performing a few operations. Space Complexity: The space complexity of the above algorithm is O(1), as we are only using a few variables. Create Quiz Comment U Utkarsh Sinha Follow 7 Improve U Utkarsh Sinha Follow 7 Improve Article Tags : C++ cpp-input-output cpp-string base-conversion cpp-stringstream +1 More Explore C++ BasicsIntroduction to C++3 min readData Types in C++6 min readVariables in C++4 min readOperators in C++9 min readBasic Input / Output in C++3 min readControl flow statements in Programming15+ min readLoops in C++7 min readFunctions in C++8 min readArrays in C++8 min readCore ConceptsPointers and References in C++5 min readnew and delete Operators in C++ For Dynamic Memory5 min readTemplates in C++8 min readStructures, Unions and Enumerations in C++3 min readException Handling in C++12 min readFile Handling in C++8 min readMultithreading in C++8 min readNamespace in C++5 min readOOP in C++Object Oriented Programming in C++8 min readInheritance in C++6 min readPolymorphism in C++5 min readEncapsulation in C++3 min readAbstraction in C++4 min readStandard Template Library(STL)Standard Template Library (STL) in C++3 min readContainers in C++ STL2 min readIterators in C++ STL10 min readC++ STL Algorithm Library3 min readPractice & ProblemsC++ Interview Questions and Answers1 min readC++ Programming Examples4 min read Like