function::strtol - Linux


Overview

strtol converts a string to a long integer. It is useful for parsing user input, reading data from files, or performing mathematical operations on strings representing numbers.

Syntax

long strtol(const char *str, char **endptr, int base);

Options/Flags

  • str: The string to be converted.
  • endptr: An optional pointer to a character pointer.
  • base: The base of the number in the string. If 0, the base is determined automatically from the string.

Examples

Simple conversion:

char *str = "123";
long num = strtol(str, NULL, 10); // Convert to base 10 (decimal)
printf("%ld\n", num); // Output: 123

Error handling:

char *str = "not a number";
char *endptr;
long num = strtol(str, &endptr, 0);
if (endptr == str) {
  // Error: Conversion failed
}

Common Issues

  • Ensure the string is in a valid numeric format for the specified base.
  • If endptr is not NULL, it points to the first character in the string that is not part of the number.
  • If the string contains invalid characters (e.g., letters), the conversion may fail.

Integration

Command chain:

echo "10101" | tr "01" "ab" | strtol -b 2

This command converts binary 10101 to decimal 21.

Script:

#!/bin/bash

# Read a number from a file
number=$(strtol $(cat number.txt) NULL 10)

# Do something with the number
echo "$number"

Related Commands

  • stoi: Converts a string to an integer
  • strtof: Converts a string to a floating-point number
  • strtold: Converts a string to a long double