简体   繁体   中英

Convert hex string to unsigned long using strtoul()

I have this silly example program that takes an input value as hex and converts it to an unsigned long integer. After conversion I printf out the result.

#include <stdio.h>

int main (int argc, char *argv[])
{

    unsigned long int id = 0;

    id = strtoul(argv[1], NULL, 16);
    printf("value: %lx\n", id);

    return 0;
}

the problem is that running this program with an hex number larger than 31-bit causes the output value to be completely wrong. The upper 32 bits are all converted into (0xf). Shouldnt strtoul() be able to handle numbers up to 2^64? Why are bits >32 garbage? The machine is a X86_64 and actually, the result is also the same with strtoull().

$ ./ex 0x7fffffff
value: 7fffffff

$ ./ex 0x80000000
value: ffffffff80000000

$ ./ex 0x3cf180000000
value: ffffffff80000000

Your solution works properly for me on my local machine. However, I believe you need to include:

#include <stdlib.h>

Strtoul is part of stdlib.

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