- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
- Related Articles
- C++ program for hexadecimal to decimal
- Program for decimal to hexadecimal conversion in C++
- Stringstream in C++
- How to Convert Decimal to Hexadecimal?
- How to Convert Hexadecimal to Decimal?
- Encoding decimal to factorial and back in JavaScript
- Stringstream in C++ programming
- How to convert Decimal to Hexadecimal in Java
- Golang Program to convert Decimal to Hexadecimal
- Golang Program to convert Hexadecimal to Decimal
- Swift Program to convert Hexadecimal to Decimal
- Swift Program to convert Decimal to Hexadecimal
- Convert decimal integer to hexadecimal number in Java
- How to Convert Decimal to Binary, Octal, and Hexadecimal using Python?
- Java Program to convert from decimal to hexadecimal
