int x = strtol(hex.c_str(), NULL, 16);
You can also use sscanf
if you want to read a partial string. You mentioned you might want to just take the first two characters:
int x;
if( 1 == sscanf(hex.c_str(), "%2x", &x) ) {
printf( "Value is: %d\n", x );
} else {
printf( "Conversion failed\n" );
}
Note the above isn't really C++. You can use the std::hex
stream modifier for that (note that I called your string mystr
this time to avoid confusion (particularly if you've imported the namespace std
):
int x;
std::istringstream iss(mystr);
bool ok = (iss >> std::hex >> x);
[edit] I notice in your comment you ask about converting to an unsigned integer. In that case, why are you not explicitly declaring your integer as unsigned int
?
For unsigned, you should use strtoul
.