Convert hex string to unsigned int issue C ++

I am currently developing code, and one of the instructions given is to get the first two digits of a hexadecimal string and perform the required operation. Everything that is less than A. is taken into account. Something more than this is not so, this is simply the next number. Which messed up the code.

Here is the line that converts it:

int x = atoi(hex.c_str);

What am I doing wrong?

+5
source share
4 answers

, , , - . , . , .

strtoul . substr() , 2 .

#include <string>
#include <cstdio>
#include <cstdlib>

int main()
{
    std::string myhex = "abcdef";
    unsigned int x = strtoul(myhex.substr(0, 2).c_str(), NULL, 16);
    printf("x = %d\n", x);
}

(.. 0xab = 171):

x = 171
+14
int x = strtol(hex.c_str(), NULL, 16);

sscanf, . , :

int x;
if( 1 == sscanf(hex.c_str(), "%2x", &x) ) {
    printf( "Value is: %d\n", x );
} else {
    printf( "Conversion failed\n" );
}

, ++. std::hex ( , mystr ( std):

int x;
std::istringstream iss(mystr);
bool ok = (iss >> std::hex >> x);

[edit] , . , unsigned int?

unsigned strtoul.

+1

atoi 10

, . strtol

. AltaVista (, , google).

+1

If you convert to unsigned, you probably want to use strtouleither with a prefix 0xor with a base 16. It may strtolalso work correctly, but this is supposed to give a signed value, so at least you can get warnings about mixing signed and unsigned from some compilers.

0
source

All Articles