Unlocking the Power of strtoull(): A Comprehensive Guide
What is strtoull()?
The strtoull()
function in C++ is a powerful tool that interprets the contents of a string as an integral number of a specified base and returns its value as an unsigned long long int. Additionally, it sets a pointer to point to the first character after the last valid character of the string, or null if there isn’t one.
How Does it Work?
The strtoull()
function takes three parameters: a string, a pointer to a character, and an integer value representing the base. It then interprets the content of the string as an integral number of the given base and returns an unsigned long long int value.
Breaking Down the Parameters
- str: A string having the representation of an integral number.
- end: A reference to an already allocated object of type
char*
. The value ofend
is set by the function to the next character instr
after the last valid character. This parameter can also be a null pointer, in which case it is not used. - base: The base of the integral value. The set of valid values for
base
is {0, 2, 3, …, 35, 36}.
Return Value
The strtoull()
function returns either an unsigned long long int value (which is converted from the string) or 0 if no valid conversion could be performed.
Examples Galore!
Let’s dive into some examples to see how strtoull()
works its magic.
Example 1: The Basics
char str[] = "123";
char* end;
unsigned long long int num = strtoull(str, &end, 10);
std::cout << "Valid integer value: " << num << std::endl;
A valid integer value for strtoull()
consists of:
- An optional + or – sign.
- A prefix 0 for octal base (applies only when
base = 8 or 0
). - A prefix 0x or 0X for hexadecimal base (applies only when
base = 16 or 0
). - A sequence of digits and/or alphabets (if base is greater than 10).
Example 2: Bases, Bases, Everywhere!
char str[] = "101";
char* end;
unsigned long long int num = strtoull(str, &end, 2);
std::cout << "Binary base: " << num << std::endl;
str[] = "A2";
end = nullptr;
num = strtoull(str, &end, 16);
std::cout << "Hexadecimal base: " << num << std::endl;
The valid values for parameter base
is {0, 2, 3,…, 35, 36}. A set of valid digits for base 2 is {0, 1}, for base 3 is {0, 1, 2} and so on.
Example 3: Leading Whitespace, Minus, and Invalid Conversion
char str[] = " -123";
char* end;
unsigned long long int num = strtoull(str, &end, 10);
std::cout << "Leading whitespace and minus sign: " << num << std::endl;
str[] = "123abc";
end = nullptr;
num = strtoull(str, &end, 10);
std::cout << "Invalid conversion: " << num << std::endl;
This example demonstrates how strtoull()
handles leading whitespace characters, minus signs, and invalid conversions.
Example 4: The Base 0 Conundrum
char str[] = "012";
char* end;
unsigned long long int num = strtoull(str, &end, 0);
std::cout << "Automatic base detection: " << num << std::endl;
In this case, the numeric base is determined automatically by looking at the format of the string.