Demystifying String to Unsigned Long Long Conversion in C++


  • Output
    It returns the unsigned long long value that the string represents. If the conversion fails (for reasons like invalid characters or exceeding the maximum value for an unsigned long long), it throws an exception.

  • Conversion
    std::stoull interprets the characters in the string str as an unsigned integer according to a specified base (which is typically between 2 and 36). By default, it assumes the base is 10 (decimal).

  • Input
    It takes two arguments:

    • The first argument is a string (str) that represents the number you want to convert.
    • The second argument (optional) is a pointer to a character (idx). This pointer, if not null, will store the location in the string where the conversion stopped. This can be useful if you want to know if the entire string was successfully converted.

Here are some additional points to note about std::stoull:

  • Error handling
    It's essential to handle potential exceptions when using std::stoull. You can do this with a try-catch block to catch any exceptions thrown during the conversion process.

  • Base specification
    You can optionally specify the base for the conversion by providing a third argument. For example, std::stoull("FF", nullptr, 16) would convert the hexadecimal string "FF" to its decimal equivalent (255).

#include <iostream>
#include <string>

int main() {
  std::string str = "12345";
  unsigned long long value;

  try {
    value = std::stoull(str);
    std::cout << "The unsigned long long value of '" << str << "' is: " << value << std::endl;
  } catch (const std::exception& e) {
    std::cerr << "Error: Conversion failed: " << e.what() << std::endl;
  }

  return 0;
}

This code will output:

The unsigned long long value of '12345' is: 12345


Converting a string with a specific base

#include <iostream>
#include <string>

int main() {
  std::string hex_str = "FF";
  unsigned long long decimal_value;

  try {
    decimal_value = std::stoull(hex_str, nullptr, 16);
    std::cout << "The decimal value of hexadecimal string '" << hex_str << "' is: " << decimal_value << std::endl;
  } catch (const std::exception& e) {
    std::cerr << "Error: Conversion failed: " << e.what() << std::endl;
  }

  return 0;
}

This code converts the hexadecimal string "FF" (representing 255) to its decimal equivalent.

Checking if the entire string was converted

#include <iostream>
#include <string>

int main() {
  std::string str = "123abc";
  unsigned long long value;
  size_t idx;

  try {
    value = std::stoull(str, &idx);
    std::cout << "Converted value: " << value << std::endl;
    
    // Check if the entire string was converted
    if (idx != str.length()) {
      std::cout << "Warning: Not all characters were converted." << std::endl;
    }
  } catch (const std::exception& e) {
    std::cerr << "Error: Conversion failed: " << e.what() << std::endl;
  }

  return 0;
}

This code checks if the entire string "123abc" could be converted. In this case, only "123" will be converted, and the code will output a warning message.

#include <iostream>
#include <string>

int main() {
  std::string invalid_str = "hello";
  unsigned long long value;

  try {
    value = std::stoull(invalid_str);
    // This line will not be reached if the conversion fails
    std::cout << "Converted value: " << value << std::endl;
  } catch (const std::invalid_argument& e) {
    std::cerr << "Error: Invalid input string." << std::endl;
  } catch (const std::out_of_range& e) {
    std::cerr << "Error: Value out of range." << std::endl;
  }

  return 0;
}


    • Included in <cstdlib> header.
    • Similar functionality to std::stoull but with some key differences:
      • Takes a char* (C-style string) as input instead of a std::string object.
      • Second argument is a char** (pointer to a character pointer) that stores the address of the first character after the converted number (similar to idx in std::stoull).
      • Does not throw exceptions on errors. It returns a specific value (typically 0) upon error, requiring manual error checking using errno.
  1. Custom conversion function

    • You can write your own function to handle string to unsigned long long conversion with specific logic.
    • This might be useful for tailored error handling or specific base conversions beyond what std::stoull offers.
  2. std::stol (C++11 and later)

    • Introduced in C++11, std::stol is a more generic function that can convert strings to various integer types based on the prefix of the string.
    • It can handle signed and unsigned integers of different sizes.
    • While not directly equivalent to std::stoull, it can be used for unsigned long long conversion if the string prefix indicates an unsigned value (e.g., "0" or "0x" for hexadecimal).
FunctionHeaderInput TypeOutput TypeException HandlingNotes
std::stoull<string>std::stringunsigned long longThrows exceptionsModern C++, safer with exception handling
std::strtoul<cstdlib>char*unsigned longNo exceptionsC-style function, manual error checking required
Custom conversion functionUser-definedstd::stringunsigned long longDepends on designFlexible but requires more code
std::stol (C++11+)<string>std::stringSigned/unsigned intThrows exceptionsMore generic, prefix-based conversion