Take each character in a string and convert it to Hex c++?

650 views Asked by At

I am trying to take a user input as a string and convert each individual element into its hex equivalent as an unsigned char in C++. For example I want to take a user input "CL" and convert that into 0x43 and 0x4C stored in an unsigned char.

string ui;
unsinged char uihex;

cout << "Please enter in command to execute: ";
cin >> ui;
for (int i=0; i<ui.length()-1; i++)
{
    uihex = static_cast<unsigned char>(ui);
}
2

There are 2 answers

4
Thomas Matthews On

If you want to print values in hexadecimal, you will need to cast the char variable to an integer type. This will help the compiler choose the correct function for printing:

char c = 'C';
cout << "0x" << hex << ((unsigned int) c) << endl;
0
2785528 On

I am trying to take a user input as a string and convert each individual element into its hex equivalent as an unsigned char in C++. For example I want to take a user input "CL" and convert that into 0x43 and 0x4C stored in an unsigned char.

No conversion is required.

char KAR = 'A'; // a char from the file
int  iKAR = static_cast<int>(KAR); // cast to an int
//
std::cout << "\nltr    hex      dec" << std::endl;
std::cout << KAR << "  == "    
          << " 0x" << std::hex     // change to hex radix
          << iKAR                  // hex: KAR cast to an int
          << "  ==  " << std::dec  // change to decimal radix
          << iKAR                  // decimal: KAR cast to an int
          << std::endl;

// output:
// ltr    hex      dec
// A  ==  0x41  ==  65