使用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 和 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);
注意:以下是我的原始答案,正如编辑所说,这不是一个完整的答案。对于功能性解决方案,请将代码粘贴在行上方:-)。
似乎因为lexical_cast<> 被定义为具有流转换语义。可悲的是,流不理解“0x”表示法。所以boost::lexical_cast 和我的手卷都不能很好地处理十六进制字符串。上述手动将输入流设置为十六进制的解决方案可以很好地处理它。
Boost has some stuff 也可以这样做,它也有一些很好的错误检查功能。你可以这样使用它:
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");