-2

Possible Duplicate:
How to convert a number to string and vice versa in C++

In C++ how do you convert a hexadecimal integer into a string representation of the decimal value of the original hex?

Let us say we have an integer whose hexadecimal representation is a1a56 (which in decimal equals 662102) and you want to convert this to a string "662102"

How would you solve this?

ps: i suggest a functional solution as an answer, feel free to shoot it down (in a polite manner, if possible)

7
  • So the hexadecimal number is orignally what type? String? int? If it's originally int then just print it out. Commented Oct 12, 2012 at 2:30
  • @nhahtdh it is int BUT i do not want to print it out, i need to manipulate the string after (let us say i am putting together a query for mysql). thanx 4 the input! Commented Oct 12, 2012 at 2:39
  • 3
    @tonygil then it is not an "hexadecimal integer". It's an integer. Numbers have no bases. Representations do. Commented Oct 12, 2012 at 2:39
  • @R.MartinhoFernandes i was just editing as per your suggestion. but you override me big time! thanx for the help clarifying the question. the only problem is that, even though it is technically correct, people search for the original title: "How to convert hex to string" (that's what's going on google). Commented Oct 12, 2012 at 2:45
  • 1
    @tony there's no "specific situation" at hand here. It's the same thing, except for a misunderstanding of the concept of number. Feel free to rollback to the old text if you think that helps with search. Commented Oct 12, 2012 at 2:53

4 Answers 4

9

You can use stringstreams:

int x = 0xa1a56;
std::stringstream ss;
ss << x;
cout << ss.str();

Or if you prefer a function:

std::string convert_int(int n)
{
   std::stringstream ss;
   ss << n;
   return ss.str();
}

Edit: Make sure you #include <sstream>

Sign up to request clarification or add additional context in comments.

Comments

6

You can read the number from a string stream as hex, and write it back to a different string stream as decimal:

int x;
istringstream iss("a1a56");
iss >> hex >> x;
ostringstream oss;
oss << x;
string s(oss.str());

Link to ideone.

Comments

4

The simplest way of doing this, using the latest version of the C++ Standard (C++11), is to use the std::to_string function:

#include <iostream>
#include <string>

int main()
{
  /* Convert: */
  std::string s { std::to_string(0xa1a56) };

  /* Print to confirm correctness: */
  std::cout << s << std::endl;
  return 0;
}

Comments

2
std::string HexDec2String(int hexIn) {
  char hexString[4*sizeof(int)+1];
  // returns decimal value of hex
  sprintf(hexString,"%i", hexIn); 
  return std::string(hexString);
}

1 Comment

char hexString[4*sizeof(int)+1]; should be enough.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.