std::stoul and std::stoull functions in C++

In this post we will learn about std::stoul and std::stoull functions in C++. You can use std::stoul function to convert a string to an unsigned long value. Also, you can use std::stoull function to convert a string to an unsigned long long value. Let’s see how these functions work.

std::stoul function in C++

unsigned long stoul(const string& s, size_t* pter, int base);
Here,
s = string object
pter = pointer/address of an object
base = determines the valid characters and their interpretation, by default its value is set to 10.

Note:

You can set the ptr parameter as nullptr (null pointer) in this case, this parameter will not be used.

The base value by default is 10 and if you put it as 0 then the base value will be decided by the format which you had used in the sequence.

std::stoull function in C++

unsigned long long stoull (const string&  s, size_t* pter = 0, int base = 10);
Here also,
s = string object 
pter = pointer/address of an object
base = determines the valid characters and their interpretation, by default its value is set to 10.

Let’s take an example, You are given two Hexadecimal strings, “3f11f27” and “b3a73ce2ff” and you want to convert them into long and long long values respectively with the help of std::stoul and std::stoull functions in a c++ program.

Hexadecimal means that we will put base = 16.

 

#include <iostream>
using namespace std;

int main()
{
        string str = "3f11f27"; 
        string str2 = "b3a73ce2ff2";
        
        //Since the strings are hexadecimal so base = 16
        unsigned long result = stoul(str, nullptr, 16); 
        unsigned long long result2 = stoull(str2, nullptr, 16);
        
        cout <<"Given Hexadecimal String 1 = " << str 
             << endl << "Given Hexadecimal String 2 = " << str2 
             << endl << "String 1 after applying std::stoul = " 
             << result  << endl 
             << "String 2 after applying std::stoull = "
             << result2 << endl; 
        return 0; 
} 

If you are not putting pter (pointer) as a null pointer, then implicitly a pointer will get the address of the first character in s.c_str(), and the index of that character will be stored in *pter, giving the total count of the characters that were processed in the conversion.

Output for the above Code

std::stoull

Now you here is a task for you!

You have to use this program for other strings like this octal string “374217447”. Remember you have to put base = 8 for octal strings.

Also, see:
std::distance() in C++

Leave a Reply

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