use std::stringstream
unsigned int x;
std::stringstream ss;
ss << std::hex << "fffefffe";
ss >> x;
下面的例子产生-65538
结果是:
#include <sstream>
#include <iostream>
int main() {
unsigned int x;
std::stringstream ss;
ss << std::hex << "fffefffe";
ss >> x;
// output it as a signed type
std::cout << static_cast<int>(x) << std::endl;
}
在新的 C++11 标准中,有一些新的实用函数可供您使用!具体来说,有一系列“字符串到数字”函数(http://en.cppreference.com/w/cpp/string/basic_string/stol and http://en.cppreference.com/w/cpp/string/basic_string/stoul)。这些本质上是 C 字符串到数字转换函数的薄包装,但知道如何处理std::string
因此,新代码的最简单答案可能如下所示:
std::string s = "0xfffefffe";
unsigned int x = std::stoul(s, nullptr, 16);
NOTE:以下是我的原始答案,正如编辑所说,这不是完整的答案。对于功能性解决方案,请将代码粘贴到该行上方:-)。
看来自从lexical_cast<>
被定义为具有流转换语义。遗憾的是,流不理解“0x”符号。所以两者boost::lexical_cast
我的手卷不能很好地处理六角弦。上面手动将输入流设置为十六进制的解决方案可以很好地处理它。
Boost 有一些东西也可以做到这一点,它也有一些很好的错误检查功能。你可以这样使用它:
try {
unsigned int x = lexical_cast<int>("0x0badc0de");
} catch(bad_lexical_cast &) {
// whatever you want to do...
}
如果您不想使用 boost,这里有一个轻量级的词法转换版本,它不进行错误检查:
template<typename T2, typename T1>
inline T2 lexical_cast(const T1 &in) {
T2 out;
std::stringstream ss;
ss << in;
ss >> out;
return out;
}
你可以这样使用:
// though this needs the 0x prefix so it knows it is hex
unsigned int x = lexical_cast<unsigned int>("0xdeadbeef");