Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert long to char* const

Tags:

c++

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)
{}
like image 955
softwarematter Avatar asked Dec 03 '22 09:12

softwarematter


2 Answers

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();
like image 72
Etienne de Martel Avatar answered Dec 31 '22 13:12

Etienne de Martel


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
like image 31
bonnyz Avatar answered Dec 31 '22 11:12

bonnyz