I need to convert an ASCII string like... "hello2" into it's decimal and or hexadecimal representation (a numeric form, the specific kind is irrelevant). So, "hello" would be : 68 65 6c 6c 6f 32 in HEX. How do I do this in C++ without just using a giant if statement?

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;
}

The only question is, how do I insert (int)sean into an integer. I actually need an integer so is there some sort of stream I can use to represent an int?

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.

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' ;
}
This article has been dead for over six months. Start a new discussion instead.