Search code examples
cstdstrtol

function strtol in C out of range... or not


I try to read a number from a string with strtol() and it returns the LONG_MAX number which is supposed to return when the number is out of range, but my number is not that big

main(){
    char linea[30]={"110111010111111000000000"};
    long num=strtol(linea,NULL,0);
    printf("%s\n%X",linea,num);
}

Actual Result:
110111010111111000000000
7FFFFFFF

Needed Result:
110111010111111000000000
DD7C00


Solution

  • According to the man page for strtol, the '0' argument you've given means 'use you best judgement', which in this case is decimal. If you want it to convert a binary number, as the 'Needed result' you've specified suggests, don't use '0', use '2'.