This is a really easy way to do it. Might be an easier/better way but this is what I put together in a few mins.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string sean = "hello2";
cout << sean << endl;
for( unsigned int i = 0; i < sean.length(); i++ )
cout << (int)sean[i] << " ";
cout << endl;
for( unsigned int i = 0; i < sean.length(); i++ )
cout << hex << (int)sean[i] << " ";
cout << endl;
return 0;
}
sfuo
Practically a Master Poster
656 posts since Jul 2009
Reputation Points: 164
Solved Threads: 99
What exactly are you trying to solve? Why do you need its hex values? Are you hashing?
firstPerson
Senior Poster
3,923 posts since Dec 2008
Reputation Points: 841
Solved Threads: 608
You can do
int jim = (int)sean[0];
cout << dec << jim << endl;
Notice that when you use cout << hex; all numbers outputted after that will be in hex so you have to type cout << dec; to convert back to decimal base.
sfuo
Practically a Master Poster
656 posts since Jul 2009
Reputation Points: 164
Solved Threads: 99
Don't really know what you are up to, but are you looking for something like this?
#include <iostream>
#include <string>
#include <cassert>
#include <stdint.h> // C99, <cstdint> in C++0x
uint64_t as_number( const std::string str )
{
const unsigned int MAX_BYTES = sizeof(uint64_t) ;
assert( str.size() <= MAX_BYTES ) ;
union
{
char cstr[ MAX_BYTES ] ;
uint64_t number ;
};
std::fill_n( cstr, MAX_BYTES, 0 ) ;
//copying in reverse is slightly saner for little-endian architectures
std::copy( str.rbegin(), str.rend(), cstr ) ;
return number ;
}
int main()
{
std::cout << as_number("hello2") << '\n' ;
}
vijayan121
Posting Virtuoso
1,606 posts since Dec 2006
Reputation Points: 1,159
Solved Threads: 287