ASCII to hexadecimal

I am trying to make application like this:

https://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=5679&lngWId=3

Here is my code:
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
using namespace std;
int main()
{
char letter;
cout << "letter:";
cin >> letter;
cout << hex << (unsigned int)letter <<endl;
system("pause");
return 0;
}


My question is how to make it to take a string and output HEX of each character?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <string>
using namespace std;

int main()
{

	cout.setf(ios::showbase);
	
	string text;
	cout << "Write text, please: ";
	cin >> text;

	for(int i = 0 ; i < text.length() ; i++)
	{
		cout << "Letter [" << dec << i << "]: "
			 << hex << (text.at(i) - '0') << "\n";
	}

}
Last edited on
For letter n I get result 0x3e.According to http://www.asciitable.com/ it should be 6e
Quentin's program does not do what you want... it only demonstrates how to use the dec and hex format modifiers.

Here is another example:
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
using namespace std;

int main()
  {
  char c = 'n';
  cout << "ASC " << c << endl               // output in ASCII
       << "OCT " << oct << (int)c << endl   // output in octal
       << "DEC " << dec << (int)c << endl   // output in decimal
       << "HEX " << hex << (int)c << endl;  // output in hexadecimal
  return 0;
  }

Hope this helps.
Last edited on
Thanks Duoas!It helped me!Here is my code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <string>
using namespace std;

int main()
{
string text;
cout << "Please write text:";
cin >> text;
for(int i = 0 ; i < text.length() ; i++)
{
cout<<hex<<(int)text[i] << "\n";
}
system("pause");
return 0;
}


After testing I have noticed when I put this for example: cout<<hex<<(int)text[i]+111 << "\n";
it gives me wrong result.
But when I add number 1 it gives me correct result.
Why it happens?

Why are you adding anything at all? If you want the numeric ASCII value, then don't do any math on it. -- It just doesn't make sense to add letters together.

With the numeric digits ('0'..'9', which are ASCII 48..57), it is common to want to convert that into the actual digit value. So, the formula is

int value = (char)digit - '0';

Hope this helps.
I was just playing with code :D
I am still beginner
Thank you again
Solved
Topic archived. No new replies allowed.