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)
{}
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 char
s:
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();
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With