StringStream in C++ for Decimal to Hexadecimal and back



In this article, we will see how to convert a Decimal to a Hexadecimal string and versa in C++. For this conversion, we are using the string stream feature of C++.

You can use StringStreams for formatting, parsing, converting a string into numeric values, and more. The Hex is an I/O manipulator. It takes a reference to an I/O stream as a parameter and returns a reference to the string after manipulating it.

Implementation of converting Decimal to Hexadecimal

In the following example, we will see how to convert decimal numbers or hexadecimal numbers in C++.

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

Following is the output of the above code:

The hexadecimal value of 61 is: 3d

So, the time complexity of the above code is O(1) as it only performs a single Operation.

Implementation of converting Hexadecimal to Decimal

In the following example, let's convert hexadecimal to decimal

#include <bits/stdc++.h>
using namespace std;
int main()
{
   string hex_str = "0x3d";
   unsigned int x;
   stringstream ss;
   ss << std::hex << hex_str;
   ss >> x;
   cout << x << endl;
   return 0;
}

Following is the output of the above code:

61

So, the time complexity of the above code is O(1) as it only performs a single Operation.

Updated on: 2025-06-06T14:18:31+05:30

828 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements