Home > database >  How to convert a string into a hexadecimal and store that hexadecimal value into a string in c
How to convert a string into a hexadecimal and store that hexadecimal value into a string in c

Time:04-01

I want to store the hex values into a string, but I don't know to do that when my string is not giving me the hex values when it is printed out. I'm pretty sure it has something to do with hex, but I don't know how to get those int values that print out the correct hex values to be stored into a string without it being changed.

I tried different ways of manipulating this and searched on the web but have not found much of a solution in solving this.

#include <iostream>
#include <string>
#include <sstream>
#include <iterator>
#include <iomanip>
#include <vector>
#include <stdlib.h>

using std::cout;
using std::endl;
using std::string;
using std::hex;
using std::stringstream;

using namespace std;

int main(){
        string s2 = "HelloWorld";

        cout << "string: " << s2 << endl;
        cout << "hexval: ";
        vector<int> character; // converting each character to its ascii value
        string bytes;
        for(int i = 0; i < s2.size(); i  ) {
            character.push_back(int(s2[i]));
            bytes = to_string(character.at(i));
            cout << hex << character.at(i) << " ";
            cout << bytes << endl;
        }
        cout << endl;
        cout << bytes << endl;
        
    return 0;
}

Here is the output that 'bytes' my string is printing out:

48 72
65 101
6c 108
6c 108
6f 111
57 87
6f 111
72 114
6c 108
64 100

Left is the hexadecimals and right is the string. Two different values. How can I store these hexadecimals that is being converted from a string be stored into a string as a hexadecimal value?

CodePudding user response:

I see 2 different ways:

The first one uses a char array and writes to it with sprintf with %X.

The second way uses a stringstream and streams the int values into it with the hex specifier. You can get the string with the .str() method of stringstream.

#include <iostream>
#include <string>
#include <sstream>
#include <iterator>
#include <iomanip>
#include <vector>
#include <stdlib.h>

using std::cout;
using std::endl;
using std::string;
using std::hex;
using std::stringstream;

using namespace std;

int main(){
    string s2 = "HelloWorld";

    cout << "string: " << s2 << endl;
    string result;
    for(int i = 0; i < s2.size(); i  ) {
        char buffer[20];
        sprintf(buffer, "%X ", s2[i]);
        result  = buffer;
    }
    cout << "hexval1: " << result << endl;

    stringstream res;
    for (int val : s2)
        res << hex << val << " ";

    cout << "hexval2: " << res.str() << endl;

    return 0;
}
  • Related