How to convert string to hexadecimal in C++

In this tutorial, we will learn to convert string to hexadecimal in C++. For this purpose, we will use a manipulator named hex.

Hex is an I/O manipulator that takes reference to an I/O stream as parameter and returns reference to the stream after manipulation.

Basically, hex can convert every integer value of the stream in to hexadecimal base. So, to convert the string into its hexadecimal version follow the below steps:

Approach:

  1. Firstly, we will take the string from the user.
  2. Now, we will process each character one by one and convert that character to its ASCII code.
  3. To convert the character to its ASCII value, we will use typecasting.
  4. Now, we will use hex manipulator to convert the ASCII value to its hexadecimal version.

The code of converting string to its hexadecimal version is given below:

#include <iostream>
#include <string>

using namespace std;


int main(){
    string s1;
    getline(cin, s1); // get the whole line as input
    cout << "string: " << s1 << endl;
    cout << "hexval: ";
    for(int i = 0; i < s1.size(); i++) {
        int character = int(s1[i]); // converting each character to its ascii value 
        cout << hex << character; // basefield is now set to hex
    }
    cout << endl;
}

Output:

Hello World
string: Hello World
hexval: 48656c6c6f20576f726c64

Check Also: how to initialize multidimensional array in c++

Leave a Reply

Your email address will not be published. Required fields are marked *