How to use stoul function In C++

The same effect could be produced using the stoul function in the bits/stdc++.h header file. 

Syntax:

unsigned long stoul (const string&  str, size_t* idx = 0, int base = 10);

Here,

str: String object with the representation of an integral number.
idx: Pointer to an object of type size_t, whose value is set by the function to position of the next character in str after the numerical value. This parameter can also be a null pointer, in which case it is not used.
base: Numerical base (radix) determines the valid characters and their interpretation. If this is 0, the base used is determined by the format in the sequence.Notice that by default this argument is 10, not 0. 

Example:

C++




// C++ program to implement stoul()
// function to convert hex string
// to a signed integer
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
   
// Driver code
int main()
{
  // Hexadecimal string
  string str = "FF";
   
  // Converting the string to
  // unsigned integer
  unsigned num = stoul(str, 0, 16);
  
  cout << str << "is equals to " << num;
  return 0;
}


Output

FFis equals to 255

Explanation: Firstly, the string contains the value FF (255). Then this string is passed as an argument to the stoul function, along with 0 (denoting null pointer) and 16 (denoting Hexadecimal conversion). The output is stored in an unsigned integer. This variable is displayed at the end. 

Convert Hex String to Signed Integer in C++

This article discusses converting a hex string to a signed integer in C++. There are 5 ways to do this in C++:

  1. Using stoi() function.
  2. Using stoul() function.
  3. Using sscanf() function.
  4. Using stringstream method.
  5. Using boost:lexical_cast.

Similar Reads

1. Using stoi function

stoi is a function in the string header file. The function takes as an argument a string and returns the converted integer. The function syntax is as follows:...

2. Using stoul function

...

3. Using sscanf function

The same effect could be produced using the stoul function in the bits/stdc++.h header file....

4. Using stringstream method

...

5. Using boost:lexical_cast

The same effect could be produced using the sscanf function in the default C++ distribution....