简体   繁体   中英

C (gcc on linux): How do i convert a hex string “0xfffffff” to an integer?

C(linux上的gcc):如何将十六进制字符串“0xfffffff”转换为整数?

 scanf("%x", &integer);
 sscanf("0xffffffff", "%x", &integer);

The other, quasi-portable, way is strtol and it's fellows strtoul , strtoll , and strtoull . They look like:

long
strtol(const char * restrict nptr, char ** restrict endptr, int base);

Use is a little strange. The first argument is the string you want to convert, and the third is the base, which for hex would be 16. The second argument is used for debugging: it can point to the first character in the hex string which failed to convert.

Ok. strtol does it.

int main()
{
    char s[] = "0xf0f0";
    unsigned int x=0;

    x = strtol(s, NULL, 16);
    printf("s = %s and x = %u\n", s, x);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM