Converting String to long Integer in C

Converting a string to a long in C is a common operation that can be useful in various programming tasks. In this post, we will explore how to use the strtol and strtoul C library functions to convert a string to a long in C.

Using strtol and strtoul

The strtol and strtoul functions are part of the C standard library and are used for converting strings to long integers. The strtol function converts a string to a long integer, while strtoul converts a string to an unsigned long integer.

Both functions take three arguments:

  • The string to convert
  • A pointer to a char pointer that points to the first invalid character in the string after the conversion
  • The base of the number system used in the string (0 for auto-detection, 2-36 for binary to base-36)

Example C code to convert a string to a long int

Here is an example code snippet that demonstrates how to use the strtol function to convert a string to a long integer:

char str[] = "12345";
char *endptr;
long num = strtol(str, &endptr, 10);

In this example, the string “12345” is converted to a long integer using the strtol function with a base of 10. The resulting long integer is stored in the num variable. The endptr pointer is used to store the position of the first invalid character in the string after the conversion.

Note that if the string being converted is not a valid long integer or if the value overflows/underflows the range of a long integer, the functions will return LONG_MAX or LONG_MIN respectively.

Using strtoll and strtoull

If you need to convert a string to a long long integer or an unsigned long long integer, you can use the strtoll and strtoull functions respectively. These functions have the same signature as strtol and strtoul, but they return a long long integer or an unsigned long long integer instead.

Example C code to convert a string to a long long int

Here is an example code snippet that demonstrates how to use the strtoll function to convert a string to a long long integer:

char str[] = "1234567890123456789";
char *endptr;
long long num = strtoll(str, &endptr, 10);

In this example, the string “1234567890123456789” is converted to a long long integer using the strtoll function with a base of 10. The resulting long long integer is stored in the num variable. The endptr pointer is used to store the position of the first invalid character in the string after the conversion.

In summary, converting a string to a long integer in C is a simple task that can be accomplished using the strtol and strtoul functions. These functions provide a convenient way to convert strings to long integers in various programming tasks. By following the steps outlined in this post, you can easily convert a string to a long integer in C and use it in your programs.

Leave a Reply

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