954,496 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Convert ASCII word into Integer

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?

dansnyderECE
Junior Poster
104 posts since Jun 2010
Reputation Points: 10
Solved Threads: 0
 

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
 

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

dansnyderECE
Junior Poster
104 posts since Jun 2010
Reputation Points: 10
Solved Threads: 0
 

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
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: