C++ 将 long 转换为 char* const
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5447316/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert long to char* const
提问by devnull
What is the right way to convert long
to char* const
in C++?
什么是转换正确的方式long
来char* const
在C ++?
EDIT:
编辑:
long l = pthread_self();
ThirdPartyFunction("Thread_Id_"+l); //Need to do this
ThirdPartyFunction(char* const identifierString)
{}
回答by Etienne de Martel
EDIT: The "proper" way to convert an integer to a string, in C++, is to use a stringstream. For instance:
编辑:在 C++ 中将整数转换为字符串的“正确”方法是使用字符串流。例如:
#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:
要将long
的内容转换为指针:
char * const p = reinterpret_cast<char * const>(your_long);
To "see" the long
as an array of char
s:
要“看到” slong
的数组char
:
char * const p = reinterpret_cast<char * const>(&your_long);
To convert the long
to a string
:
将 转换long
为 a string
:
std::ostringstream oss;
oss << your_long;
std::string str = oss.str();
// optionaly:
char * const p = str.c_str();
回答by bonnyz
Another possibile "pure" solution is to use snprintf
另一种可能的“纯”解决方案是使用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
回答by Michael J
long l=0x7fff0000; // or whatever
char const *p = reinterpret_cast<char const *>(l);