4

What is the right way to convert long to char* const in C++?

EDIT:

long l = pthread_self();
ThirdPartyFunction("Thread_Id_"+l); //Need to do this


ThirdPartyFunction(char* const identifierString)
{}
softwarematter
  • 28,015
  • 64
  • 169
  • 263

3 Answers3

10

EDIT: The "proper" way to convert an integer to a string, in C++, is to use a stringstream. For instance:

#include <sstream>

std::ostringstream oss;
oss << "Thread_Id_" << l;
ThirdPartyFunction(oss.str().c_str());

Now, that probably won't be the "fastest" way (streams have some overhead), but it's simple, readable, and more importantly, safe.


OLD ANSWER BELOW

Depends on what you mean by "convert".

To convert the long's contents to a pointer:

char * const p = reinterpret_cast<char * const>(your_long);

To "see" the long as an array of chars:

char * const p = reinterpret_cast<char * const>(&your_long);

To convert the long to a string:

std::ostringstream oss;
oss << your_long;
std::string str = oss.str();
// optionaly:
char * const p = str.c_str();
Etienne de Martel
  • 34,692
  • 8
  • 91
  • 111
6

Another possibile "pure" solution is to use snprintf

long number = 322323l;
char buffer [128];
int ret = snprintf(buffer, sizeof(buffer), "%ld", number);
char * num_string = buffer; //String terminator is added by snprintf
bonnyz
  • 13,458
  • 5
  • 46
  • 70
1
long l=0x7fff0000;   // or whatever
char const *p = reinterpret_cast<char const *>(l);
Michael J
  • 7,631
  • 2
  • 24
  • 30