How to use C++ STL stoul() function In C++
This is an STL function in C++11 that is defined in the header file <string>, which is also used to convert a string to an integer.
Syntax:
stoul (const string& str, size_t* idx, int base);
Parameters:
- str: Input string, with the representation of an integral number.
- idx: Pointer to an object of type size_t, whose value is set by 0. It can also be null pointer, in which case it is not used.
- base: Numerical base(radix) that determines the valid characters and their interpretation. Here it will be 16, as it’s a hexadecimal string.
Below is the C++ program to convert a hex string to an Integer using stoul() function:
C++
// C++ program to convert a hex string // to an Integer using stoul() function #include<bits/stdc++.h> using namespace std; // Driver code int main() { string s = "DD" ; // Converting a hexadecimal string // to an integer // Initializing the return integer // value of the function to a // new variable int i = stoul(s, 0, 16); cout << i << endl; return 0; } |
Output
221
Different Ways to Convert Hex String to Integer in C++ STL
A hexadecimal number is a number whose base is 16. has numerals 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, and 15. And 10, 11, 12, 13, 14, and 15 these numbers are denoted by A, B, C, D, E, F. In C++ STL there are certain properties that help to convert a hexadecimal string or number to a decimal number easily.
There are 5 different ways to convert a Hex string to an Integer in C++:
- Using stoi() function
- Using sscanf() function
- Using stoul() function
- Using string stream method
- Using boost:lexical_cast function
Let’s start discussing each of these methods in detail.