C: converting string to long

Posted on In QA

How to convert a string to long in C?

Use strtol or strtoul C library:

strtol man page.
strtoul man page.

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. A decimal constant begins with a non-zero digit, and consists of a sequence of decimal digits. An octal constant consists of the prefix ‘0’ optionally followed by a sequence of the digits ‘0’ to ‘7’ only. A hexadecimal constant consists of the prefix 0x or 0X followed by a sequence of the decimal digits and letters ‘a’ (or ‘A’ ) to ‘f’ (or ‘F’ ) with values 10 to 15 respectively.

One piece of example code:

    long size = strtol(result, NULL, 0);

here, result is a string.

Leave a Reply

Your email address will not be published. Required fields are marked *