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

998 views Asked by At

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

2

There are 2 answers

0
brepro On BEST ANSWER

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'.

4
Hunter McMillen On

probably because you pass in base 0

try:

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

EDIT Apparently base 0 is a special value for the strtol function:

If the value of base is 0, the expected form of the subject sequence is that of a decimal constant, octal constant, or hexadecimal constant, any of which may be preceded by a '+' or '-' sign.

So I guess you can use 0, sorry for doubting you.