Convert String to Hexadecimal

Hello, I want to convert a string to its equivalent hexadecimal value.
I already convert the string to char array, but I dont know how to convert the char array I have into its hexadecimal equivalent. Please help me TIA :)
Example:
The output must be like this.
Hello World! = 0x48 0x65 0x6c 0x6c 0x6f 0x20 0x57 0x6f 0x72 0x6c 0x64 0x21
1
2
3
4
5
6
7
8
# include <iostream>
# include <iomanip>
int main() {
  for (char const elt: "My char array") 
    std::cout << "0x" << std::hex << std::setw(2) << std::setfill('0')
              << static_cast<int>(elt) << ' ';
  std::cout << '\n';
}

http://coliru.stacked-crooked.com/a/07d4ac64f425d7ba
Is there's a way that the hex value is in long long not in string?
Like this?
1
2
long long const my_long_long = 1234ll;
std::cout << std::hex << my_long_long << '\n'; 

Thanks men for the help, I already figure it out. In c++ if you declare a character as a long long the output is automatically a long long number.
For example.

long long x = 'A';
cout << x << endl;

The output is 65, which is the output I want to have.
you don't need to waste so much space or do it this way. char and unsigned char are integer types. cout will try to be smart and print them as character symbols on the screen, but you can override that by simply casting it. That is, what I am saying is that 'A' actually IS 65 and there is special logic under the hood that prints the 'A' symbol instead of the number. all you needed was

cout << (int)x << endl;


your code converts 1 byte into 8, 7 of which are unused. This would add up to a lot of wasted space if you are doing anything in bulk. If its just the one, its not that big a deal.

The concept that char IS an int is very important because there will be times when you need 'bytes' instead of 'letters', so keep it in mind for when that comes around in a program.

and finally, 65 is NOT hex. You need to tell cout to print hex if you want hex. I mean, 65 is legal hex, but its not the hex value of 'A'. Its the base 10 value. The hex value of 'A' is 41 ...
Last edited on
Topic archived. No new replies allowed.