Convert String to Hex in C++ using std::hex


In this article, we are going to learn, how to Convert String to Hex in C++ using std::hex. We will learn this by using multiple below techniques.

  • Convert String to Hex in C++ using std::hex
  • Using std::stringstream and std::hex to Convert String to Hex Value in C++

1. Convert String to Hex in C++ using std::hex


In this example, we are going to use the std::hex I/O manipulator. C++ provides a std::hex I/O manipulator that can modify the stream data’s number base.

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string str = "DevEnum.com";

    cout << "Hexadecimal Equivalent of String =  "<< str << " is :";
	
    for (const auto &item : str) 
	{
        cout << hex << int(item);
    }
    cout << endl;

    return 0;
}

Output

Hexadecimal Equivalent of String =  DevEnum.com is :446576456e756d2e636f6d

2. Using std::stringstream and std::hex to Convert String to Hex


In this example also, we are going to use the std::hex I/O manipulator. C++ provides a std::hex I/O manipulator that can modify the stream data’s number base. Here we are not using the pure string like in the above example, instead, we are using the stringstream to print the string with its hex equivalent.

#include <iostream>
#include <string>
#include <sstream>

using namespace std;

int main()
{
    string str = "DevEnum.com";
    string str1;
    stringstream sstrm;

    for (const auto &item : str) 
	{
        sstrm << hex << int(item);
    }
    str1 = sstrm.str();

	cout << "Hexadecimal Equivalent of String =  "<< str << " is :" << str1;

    return 0;
}

Output

Hexadecimal Equivalent of String =  DevEnum.com is :446576456e756d2e636f6d