문제

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

도움이 되었습니까?

해결책

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

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top