VOOZH about

URL: https://www.geeksforgeeks.org/c/converting-string-to-long-in-c/

⇱ Converting String to Long in C - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Converting String to Long in C

Last Updated : 23 Jul, 2025

Here, we will see how to build a C Program For String to Long Conversion using strtol() function.

Syntax:

long int strtol(char *string, char **ptr, int base)
  1. The first argument is given as a string
  2. The second argument is a reference to an object of type char*
  3. The third argument denotes the base in which the number is represented. To know more about visit strtol() function.

Note: We don't have to use long int in the case of strtoul() because the range of unsigned long is greater than long on the positive front. 
[long : -2147483648 to 2147483647 and unsigned long : 0 to 4294967295]

Syntax:
strtoul(char *string, char **ptr, int base) // no long int need in strtoul()


Output
Number is 1234567890

Output
Integer part is 100
String part is GeeksforGeeks

Method: Using atol() function 


Output
l = 349639

Method: Using ltoa() 

Output

string is 1234

Method: Without Inbuilt Function


Output
Number is 123456789

Approach name: String to Long Conversion using Custom Algorithm

Steps:

  1. Initialize a variable 'result' to zero.
  2. Iterate through each character of the input string:
    a. Multiply the result by 10.
    b. Convert the current character to a digit by subtracting the ASCII value of '0'.
    c. Add the digit to the result.
  3. Return the result.

Output
123456789

Time complexity: O(n), where n is the length of the input string.
Auxiliary space: O(1)

Method: Using sscanf() function

Here's another approach to convert a string to a long integer in C:

  • Include the "stdlib.h" and "stdio.h" header files in your program.
  • Define a string variable to hold the input string.
  • Use the "sscanf()" function to read the long integer from the input string
  • Print the long integer using the "printf()" function.

Output
123456789

Time complexity: The time complexity of the "sscanf()" function is O(n), where n is the length of the input string.

Auxiliary space: The space complexity of the program is O(1), as we are not using any additional data structures to perform the conversion.

Comment