marcin
marcin

Reputation: 125

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"). Whats the quickest/nice/safe way to compare if the values of strInt and strHex are equal(numerically)?

Need to exclude sprintf to prevent buffer overflow Also cant use snprintf - my compiler does not support c++ 11

Thank you all in advance

Upvotes: 0

Views: 9225

Answers (2)

user529758
user529758

Reputation:

I don't see how the sprintf() or snprintf() function would be needed for this.

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;

Upvotes: 3

Jorge N&#250;&#241;ez
Jorge N&#250;&#241;ez

Reputation: 1772

Use strtol to convert both to integer and then compare them. You can use strHex.c_str() to convert from c++ string to the c-style string required by strtol.

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);

Upvotes: 3

Related Questions