我想在C++中将十六进制字符串转换为32位有符号整数。
例如,我有一个十六进制字符串"fffefffe“。它的二进制表示是1111111111111010111111111111111111111110。它的带符号整数表示是:-65538。
如何在C++中执行此转换?这也需要对非负数起作用。例如,十六进制字符串"0000000A",它是二进制的0000000000000000000000000000000000001010和十进制的10。
发布于 2009-07-01 10:03:47
对于同时使用C和C++的方法,您可能需要考虑使用标准库函数strtol()。
#include <cstdlib>
#include <iostream>
using namespace std;
int main() {
string s = "abcd";
char * p;
long n = strtol( s.c_str(), & p, 16 );
if ( * p != 0 ) { //my bad edit was here
cout << "not a number" << endl;
}
else {
cout << n << endl;
}
}
发布于 2010-01-17 02:08:05
Andy Buchanan,就坚持使用C++而言,我喜欢你的,但我有几个mod:
template <typename ElemT>
struct HexTo {
ElemT value;
operator ElemT() const {return value;}
friend std::istream& operator>>(std::istream& in, HexTo& out) {
in >> std::hex >> out.value;
return in;
}
};
使用方式如下
uint32_t value = boost::lexical_cast<HexTo<uint32_t> >("0x2a");
这样,您就不需要为每个int类型执行一次impl。
发布于 2009-07-01 22:03:47
使用strtoul
的工作示例如下:
#include <cstdlib>
#include <iostream>
using namespace std;
int main() {
string s = "fffefffe";
char * p;
long n = strtoul( s.c_str(), & p, 16 );
if ( * p != 0 ) {
cout << "not a number" << endl;
} else {
cout << n << endl;
}
}
strtol
将string
转换为long
。在我的电脑上,numeric_limits<long>::max()
给了0x7fffffff
。显然,0xfffefffe
比0x7fffffff
更重要。因此,strtol
返回MAX_LONG
而不是所需的值。strtoul
将string
转换为unsigned long
,这就是在这种情况下没有溢出的原因。
好的,在转换之前,strtol
正在考虑输入字符串,而不是32位有符号整数。strtol
的有趣示例
#include <cstdlib>
#include <iostream>
using namespace std;
int main() {
string s = "-0x10002";
char * p;
long n = strtol( s.c_str(), & p, 16 );
if ( * p != 0 ) {
cout << "not a number" << endl;
} else {
cout << n << endl;
}
}
上面的代码在控制台中打印-65538
。
https://stackoverflow.com/questions/1070497
复制相似问题