[英]The easiest way to compare string containing integer to string containing hex
I have two strings one with integer (eg string strInt = "100") and one with hex number (eg string strHex = "0x64"). 我有两个字符串,一个是整数(例如,字符串strInt =“ 100”),另一个是十六进制数字(例如,字符串strHex =“ 0x64”)。 Whats the quickest/nice/safe way to compare if the values of strInt and strHex are equal(numerically)? 如果strInt和strHex的值相等(数值)相等,最快/最安全/比较的方法是什么?
Need to exclude sprintf to prevent buffer overflow Also cant use snprintf - my compiler does not support c++ 11 需要排除sprintf以防止缓冲区溢出也不能使用snprintf-我的编译器不支持c ++ 11
Thank you all in advance 谢谢大家
Use strtol
to convert both to integer and then compare them. 使用strtol
将两者都转换为整数,然后进行比较。 You can use strHex.c_str()
to convert from c++ string to the c-style string required by strtol
. 您可以使用strHex.c_str()
将c ++字符串转换为strtol
所需的c样式字符串。
Example: 例:
long int numHex = strtol(strHex.c_str(),NULL,16); // 16 is the base of the source
long int numInt = strtol(strInt.c_str(),NULL,10);
I don't see how the sprintf()
or snprintf()
function would be needed for this. 我没有看到为此需要sprintf()
或snprintf()
函数。
std::string a = "1337";
std::string b = "0x539";
std::stringstream as;
as.str(a);
std::stringstream bs;
bs.str(b);
int na, nb;
as >> na;
bs >> std::hex >> nb;
std::cout << a << " is " << (na == nb ? "equal" : "not equal") << " to " << b << std::endl;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.